@burdenoff/be-sdk 2026.1127.1 → 2026.1128.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/index.d.ts +1 -1
- package/dist/feature-flags/index.d.ts +1 -1
- package/dist/{index-CkQieKSy.d.ts → index-12NbzOYy.d.ts} +1 -1
- package/dist/{index-DFEKBKBE.d.ts → index-BQ5O967l.d.ts} +1 -1
- package/dist/{index-BwgBHUuX.d.ts → index-CkB68nQA.d.ts} +2 -2
- package/dist/{index-BgOU0pxB.d.ts → index-jStzN9rq.d.ts} +6 -2
- package/dist/{index-CUiL43SY.d.ts → index-tLd9b-nS.d.ts} +2 -2
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/instrumentation/index.d.ts +2 -2
- package/dist/instrumentation/index.js +2 -2
- package/dist/{instrumentation-C738xDj8.js → instrumentation-DKHAGCoz.js} +107 -4
- package/dist/instrumentation-DKHAGCoz.js.map +1 -0
- package/dist/prisma/index.d.ts +3 -3
- package/dist/prisma/index.js +3 -3
- package/dist/{prisma-J-ZUmVWJ.js → prisma-1J9WTyAF.js} +11 -2
- package/dist/{prisma-J-ZUmVWJ.js.map → prisma-1J9WTyAF.js.map} +1 -1
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +24 -10
- package/dist/server/index.js.map +1 -1
- package/dist/{stub-BUnfMiAS.js → stub-DZ332ZHG.js} +2 -2
- package/dist/{stub-BUnfMiAS.js.map → stub-DZ332ZHG.js.map} +1 -1
- package/dist/telemetry/index.d.ts +1 -1
- package/dist/telemetry/index.js +1 -1
- package/dist/tracker/index.js +2 -2
- package/dist/{tracker-B1fEAM3i.js → tracker-DE4MDVTr.js} +2 -2
- package/dist/{tracker-B1fEAM3i.js.map → tracker-DE4MDVTr.js.map} +1 -1
- package/dist/{types-BWN8tMdF.d.ts → types-oV9uAkMA.d.ts} +1 -1
- package/dist/{workspace-extension-COrC0dYi.js → workspace-extension-ByopOwtK.js} +260 -62
- package/dist/workspace-extension-ByopOwtK.js.map +1 -0
- package/dist/{workspace-extension-DTFTdGVF.d.ts → workspace-extension-DKxDI4H6.d.ts} +14 -1
- package/package.json +1 -1
- package/dist/instrumentation-C738xDj8.js.map +0 -1
- package/dist/workspace-extension-COrC0dYi.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentation-C738xDj8.js","names":["instrumentedContext","defaultLogger","getTracerFn","getMetricsFn","getConfig","isConfigInit","isTracerInit","isMetricsInit"],"sources":["../src/instrumentation/tracer.ts","../src/telemetry/logger-state.ts","../src/instrumentation/types.ts","../src/instrumentation/graphql-plugin.ts","../src/instrumentation/decorators.ts","../src/instrumentation/index.ts"],"sourcesContent":["/**\n * Tracer Module\n *\n * OpenTelemetry tracing utilities for distributed tracing across\n * Burdenoff microservices. Provides span creation, context propagation,\n * and trace management.\n *\n * @module instrumentation/tracer\n * @category Observability\n */\n\nimport { logger } from '../logger/index.js';\nimport { getInstrumentationConfig, isFeatureEnabled, isInstrumentationConfigInitialized } from './config.js';\nimport type { OperationContext, SpanAttributes, SpanContext, TraceContext } from './types.js';\n\n/**\n * Span status\n */\nexport enum SpanStatus {\n UNSET = 0,\n OK = 1,\n ERROR = 2,\n}\n\n/**\n * Span kind\n */\nexport enum SpanKind {\n INTERNAL = 0,\n SERVER = 1,\n CLIENT = 2,\n PRODUCER = 3,\n CONSUMER = 4,\n}\n\n/**\n * Span interface for tracing operations\n */\nexport interface Span {\n /** Span name */\n name: string;\n /** Trace ID */\n traceId: string;\n /** Span ID */\n spanId: string;\n /** Parent span ID */\n parentSpanId?: string;\n /** Span kind */\n kind: SpanKind;\n /** Start time in milliseconds */\n startTime: number;\n /** End time in milliseconds */\n endTime?: number;\n /** Span status */\n status: SpanStatus;\n /** Span attributes */\n attributes: SpanAttributes;\n /** Events recorded in this span */\n events: SpanEvent[];\n /** Whether the span is recording */\n isRecording: boolean;\n\n /** Set an attribute on the span */\n setAttribute(key: string, value: string | number | boolean): Span;\n /** Set multiple attributes on the span */\n setAttributes(attributes: SpanAttributes): Span;\n /** Set the span status */\n setStatus(status: SpanStatus, message?: string): Span;\n /** Record an exception */\n recordException(error: Error): Span;\n /** Add an event to the span */\n addEvent(name: string, attributes?: SpanAttributes): Span;\n /** End the span */\n end(): void;\n /** Get span context for propagation */\n getSpanContext(): SpanContext;\n}\n\n/**\n * Span event\n */\nexport interface SpanEvent {\n name: string;\n timestamp: number;\n attributes?: SpanAttributes;\n}\n\n/**\n * Generate a random trace ID (32 hex characters)\n */\nfunction generateTraceId(): string {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Generate a random span ID (16 hex characters)\n */\nfunction generateSpanId(): string {\n const bytes = new Uint8Array(8);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * In-memory span implementation\n */\nclass InMemorySpan implements Span {\n name: string;\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n kind: SpanKind;\n startTime: number;\n endTime?: number;\n status: SpanStatus = SpanStatus.UNSET;\n attributes: SpanAttributes = {};\n events: SpanEvent[] = [];\n isRecording = true;\n\n private onEnd?: (span: Span) => void;\n\n constructor(\n name: string,\n kind: SpanKind = SpanKind.INTERNAL,\n parentContext?: SpanContext,\n onEnd?: (span: Span) => void\n ) {\n this.name = name;\n this.kind = kind;\n this.startTime = Date.now();\n this.spanId = generateSpanId();\n this.onEnd = onEnd;\n\n if (parentContext) {\n this.traceId = parentContext.traceId;\n this.parentSpanId = parentContext.spanId;\n } else {\n this.traceId = generateTraceId();\n }\n }\n\n setAttribute(key: string, value: string | number | boolean): Span {\n if (this.isRecording) {\n this.attributes[key] = value;\n }\n return this;\n }\n\n setAttributes(attributes: SpanAttributes): Span {\n if (this.isRecording) {\n Object.assign(this.attributes, attributes);\n }\n return this;\n }\n\n setStatus(status: SpanStatus, message?: string): Span {\n this.status = status;\n if (message) {\n this.attributes['status.message'] = message;\n }\n return this;\n }\n\n recordException(error: Error): Span {\n this.status = SpanStatus.ERROR;\n this.attributes['error'] = true;\n this.attributes['error.type'] = error.name;\n this.attributes['error.message'] = error.message;\n if (error.stack) {\n this.attributes['error.stack'] = error.stack;\n }\n this.addEvent('exception', {\n 'exception.type': error.name,\n 'exception.message': error.message,\n });\n return this;\n }\n\n addEvent(name: string, attributes?: SpanAttributes): Span {\n if (this.isRecording) {\n this.events.push({\n name,\n timestamp: Date.now(),\n attributes,\n });\n }\n return this;\n }\n\n end(): void {\n if (!this.isRecording) return;\n\n this.endTime = Date.now();\n this.isRecording = false;\n\n if (this.onEnd) {\n this.onEnd(this);\n }\n }\n\n getSpanContext(): SpanContext {\n return {\n traceId: this.traceId,\n spanId: this.spanId,\n traceFlags: this.status === SpanStatus.ERROR ? 1 : 0,\n };\n }\n}\n\n/**\n * No-op span for when tracing is disabled\n */\nclass NoOpSpan implements Span {\n name = '';\n traceId = '';\n spanId = '';\n kind = SpanKind.INTERNAL;\n startTime = 0;\n status = SpanStatus.UNSET;\n attributes: SpanAttributes = {};\n events: SpanEvent[] = [];\n isRecording = false;\n\n setAttribute(): Span {\n return this;\n }\n setAttributes(): Span {\n return this;\n }\n setStatus(): Span {\n return this;\n }\n recordException(): Span {\n return this;\n }\n addEvent(): Span {\n return this;\n }\n end(): void {}\n getSpanContext(): SpanContext {\n return { traceId: '', spanId: '', traceFlags: 0 };\n }\n}\n\n/**\n * Tracer class for creating and managing spans\n */\nexport class Tracer {\n private serviceName: string;\n private activeSpans: Map<string, Span> = new Map();\n private currentSpan: Span | null = null;\n private spanListeners: Array<(span: Span) => void> = [];\n\n constructor(serviceName: string) {\n this.serviceName = serviceName;\n }\n\n /**\n * Check if tracing is enabled\n */\n isEnabled(): boolean {\n return isInstrumentationConfigInitialized() && isFeatureEnabled('tracing');\n }\n\n /**\n * Start a new span\n */\n startSpan(name: string, kind: SpanKind = SpanKind.INTERNAL, parentContext?: SpanContext): Span {\n if (!this.isEnabled()) {\n return new NoOpSpan();\n }\n\n const config = getInstrumentationConfig();\n\n // Check if operation should be ignored\n if (config.tracing.ignoredOperations?.includes(name)) {\n return new NoOpSpan();\n }\n\n // Use current span as parent if no parent provided\n const parent = parentContext || this.currentSpan?.getSpanContext();\n\n const span = new InMemorySpan(name, kind, parent, (completedSpan) => {\n this.onSpanEnd(completedSpan);\n });\n\n // Add service attributes\n span.setAttributes({\n 'service.name': this.serviceName,\n 'service.version': config.tracing.serviceVersion || '1.0.0',\n 'deployment.environment': config.tracing.environment || 'development',\n });\n\n // Add custom resource attributes\n if (config.tracing.resourceAttributes) {\n span.setAttributes(config.tracing.resourceAttributes);\n }\n\n // Track active span\n this.activeSpans.set(span.spanId, span);\n this.currentSpan = span;\n\n return span;\n }\n\n /**\n * Start a span from operation context\n */\n startSpanFromContext(context: OperationContext, kind: SpanKind = SpanKind.INTERNAL): Span {\n const span = this.startSpan(context.operationName, kind);\n\n if (span.isRecording) {\n span.setAttributes({\n 'operation.type': context.operationType,\n ...(context.actorId && { 'actor.id': context.actorId }),\n ...(context.tenantId && { 'tenant.id': context.tenantId }),\n ...(context.workspaceId && { 'workspace.id': context.workspaceId }),\n ...(context.requestId && { 'request.id': context.requestId }),\n ...context.attributes,\n });\n }\n\n return span;\n }\n\n /**\n * Get current active span\n */\n getCurrentSpan(): Span | null {\n return this.currentSpan;\n }\n\n /**\n * Get current trace context for logging\n */\n getTraceContext(): TraceContext {\n if (!this.currentSpan || !this.isEnabled()) {\n return {};\n }\n\n const spanContext = this.currentSpan.getSpanContext();\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceFlags: spanContext.traceFlags,\n parentSpanId: this.currentSpan.parentSpanId,\n };\n }\n\n /**\n * Set current span (for context propagation)\n */\n setCurrentSpan(span: Span): void {\n this.currentSpan = span;\n }\n\n /**\n * Run a function within a span\n */\n async withSpan<T>(\n name: string,\n fn: (span: Span) => Promise<T>,\n kind: SpanKind = SpanKind.INTERNAL,\n parentContext?: SpanContext\n ): Promise<T> {\n const span = this.startSpan(name, kind, parentContext);\n\n try {\n const result = await fn(span);\n span.setStatus(SpanStatus.OK);\n return result;\n } catch (error) {\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n }\n\n /**\n * Run a synchronous function within a span\n */\n withSpanSync<T>(\n name: string,\n fn: (span: Span) => T,\n kind: SpanKind = SpanKind.INTERNAL,\n parentContext?: SpanContext\n ): T {\n const span = this.startSpan(name, kind, parentContext);\n\n try {\n const result = fn(span);\n span.setStatus(SpanStatus.OK);\n return result;\n } catch (error) {\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n }\n\n /**\n * Add a listener for completed spans\n */\n addSpanListener(listener: (span: Span) => void): void {\n this.spanListeners.push(listener);\n }\n\n /**\n * Remove a span listener\n */\n removeSpanListener(listener: (span: Span) => void): void {\n const index = this.spanListeners.indexOf(listener);\n if (index !== -1) {\n this.spanListeners.splice(index, 1);\n }\n }\n\n /**\n * Handle span completion\n */\n private onSpanEnd(span: Span): void {\n // Remove from active spans\n this.activeSpans.delete(span.spanId);\n\n // Update current span to parent if this was the current span\n if (this.currentSpan?.spanId === span.spanId) {\n if (span.parentSpanId) {\n this.currentSpan = this.activeSpans.get(span.parentSpanId) || null;\n } else {\n this.currentSpan = null;\n }\n }\n\n // Log span if console exporter enabled\n const config = getInstrumentationConfig();\n if (config.tracing.exporterType === 'console') {\n this.logSpan(span);\n }\n\n // Notify listeners\n for (const listener of this.spanListeners) {\n try {\n listener(span);\n } catch (error) {\n logger.error('[Tracer] Error in span listener:', error);\n }\n }\n }\n\n /**\n * Log span to console (for debugging)\n */\n private logSpan(span: Span): void {\n const duration = span.endTime ? span.endTime - span.startTime : 0;\n\n logger.debug('[Tracer] Span completed', {\n name: span.name,\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n kind: SpanKind[span.kind],\n status: SpanStatus[span.status],\n duration: `${duration}ms`,\n attributes: span.attributes,\n eventCount: span.events.length,\n });\n }\n\n /**\n * Get active span count\n */\n getActiveSpanCount(): number {\n return this.activeSpans.size;\n }\n\n /**\n * Clear all active spans (for testing)\n */\n clearActiveSpans(): void {\n this.activeSpans.clear();\n this.currentSpan = null;\n }\n}\n\n/**\n * Global tracer instance\n */\nlet globalTracer: Tracer | null = null;\n\n/**\n * Initialize global tracer\n */\nexport function initializeTracer(serviceName: string): Tracer {\n globalTracer = new Tracer(serviceName);\n return globalTracer;\n}\n\n/**\n * Get global tracer instance\n */\nexport function getTracer(): Tracer {\n if (!globalTracer) {\n // Return a default tracer if not initialized\n globalTracer = new Tracer('unknown-service');\n }\n return globalTracer;\n}\n\n/**\n * Check if tracer is initialized\n */\nexport function isTracerInitialized(): boolean {\n return globalTracer !== null;\n}\n\n/**\n * Convenience function to start a span\n */\nexport function startSpan(name: string, kind: SpanKind = SpanKind.INTERNAL, parentContext?: SpanContext): Span {\n return getTracer().startSpan(name, kind, parentContext);\n}\n\n/**\n * Convenience function to run code within a span\n */\nexport async function withSpan<T>(\n name: string,\n fn: (span: Span) => Promise<T>,\n kind: SpanKind = SpanKind.INTERNAL\n): Promise<T> {\n return getTracer().withSpan(name, fn, kind);\n}\n\n/**\n * Convenience function to get current trace context\n */\nexport function getTraceContext(): TraceContext {\n return getTracer().getTraceContext();\n}\n\n/**\n * Extract trace context from HTTP headers (W3C Trace Context format)\n */\nexport function extractTraceContext(headers: Record<string, string | string[] | undefined>): SpanContext | undefined {\n const traceparent = headers['traceparent'];\n if (!traceparent) return undefined;\n\n const value = Array.isArray(traceparent) ? traceparent[0] : traceparent;\n if (!value) return undefined;\n\n // Parse W3C traceparent: version-trace_id-parent_id-trace_flags\n const parts = value.split('-');\n if (parts.length !== 4) return undefined;\n\n const [, traceId, spanId, traceFlags] = parts;\n if (!traceId || !spanId || traceId.length !== 32 || spanId.length !== 16) {\n return undefined;\n }\n\n return {\n traceId,\n spanId,\n traceFlags: parseInt(traceFlags || '0', 16),\n isRemote: true,\n };\n}\n\n/**\n * Inject trace context into HTTP headers (W3C Trace Context format)\n */\nexport function injectTraceContext(headers: Record<string, string>, spanContext?: SpanContext): void {\n const context = spanContext || getTracer().getCurrentSpan()?.getSpanContext();\n if (!context || !context.traceId || !context.spanId) return;\n\n // Format: version-trace_id-parent_id-trace_flags\n headers['traceparent'] =\n `00-${context.traceId}-${context.spanId}-${context.traceFlags.toString(16).padStart(2, '0')}`;\n}\n","import type { Logger } from '../logger/index.js';\n\nlet activeTelemetryLogger: Logger | undefined;\n\nexport function setActiveTelemetryLogger(logger: Logger): void {\n activeTelemetryLogger = logger;\n}\n\nexport function getActiveTelemetryLogger(): Logger | undefined {\n return activeTelemetryLogger;\n}\n","/**\n * Instrumentation Types\n *\n * Type definitions for OpenTelemetry instrumentation configuration\n * and utilities used across all Burdenoff microservices.\n *\n * @module instrumentation/types\n * @category Observability\n */\n\n/**\n * Instrumentation feature flags for conditional enable/disable\n */\nexport interface InstrumentationFeatureFlags {\n /** Enable distributed tracing with spans */\n tracing: boolean;\n /** Enable metrics collection (counters, histograms, gauges) */\n metrics: boolean;\n /** Enable enhanced logging with trace context */\n logging: boolean;\n /** Enable GraphQL resolver instrumentation */\n graphql: boolean;\n /** Enable database query instrumentation */\n database: boolean;\n /** Enable HTTP request/response instrumentation */\n http: boolean;\n /** Enable cache operation instrumentation */\n cache: boolean;\n /** Enable event queue instrumentation */\n eventQueue: boolean;\n}\n\n/**\n * Tracing configuration\n */\nexport interface TracingConfig {\n /** Enable tracing (default: true when instrumentation enabled) */\n enabled: boolean;\n /** Service name for traces */\n serviceName: string;\n /** Service version */\n serviceVersion?: string;\n /** Environment (development, staging, production) */\n environment?: string;\n /** OTLP exporter endpoint (e.g., http://localhost:4318) */\n exporterEndpoint?: string;\n /** Exporter type: 'otlp' | 'console' | 'none' */\n exporterType?: 'otlp' | 'console' | 'none';\n /** Trace sampling rate (0-1, default: 1.0) */\n samplingRate?: number;\n /** Propagation format: 'w3c' | 'b3' | 'jaeger' */\n propagationFormat?: 'w3c' | 'b3' | 'jaeger';\n /** Additional resource attributes */\n resourceAttributes?: Record<string, string>;\n /** Ignored routes (won't create spans) */\n ignoredRoutes?: string[];\n /** Ignored operations (won't create spans) */\n ignoredOperations?: string[];\n}\n\n/**\n * Metrics configuration\n */\nexport interface MetricsConfig {\n /** Enable metrics (default: true when instrumentation enabled) */\n enabled: boolean;\n /** Service name for metrics */\n serviceName: string;\n /** OTLP exporter endpoint */\n exporterEndpoint?: string;\n /** Exporter type: 'otlp' | 'prometheus' | 'console' | 'none' */\n exporterType?: 'otlp' | 'prometheus' | 'console' | 'none';\n /** Prometheus metrics endpoint (default: /metrics) */\n prometheusEndpoint?: string;\n /** Prometheus metrics port (default: 9090) */\n prometheusPort?: number;\n /** Metrics collection interval in ms (default: 60000) */\n collectInterval?: number;\n /** Enable default runtime metrics (CPU, memory, etc.) */\n defaultMetrics?: boolean;\n /** Custom metric prefix */\n metricPrefix?: string;\n /** Maximum distinct label series per metric before bucketing into overflow (default: 500) */\n maxSeriesPerMetric?: number;\n /** Process-level cap on total distinct metric label series across the registry (default: 5000) */\n maxTotalSeries?: number;\n}\n\n/**\n * Logging configuration for instrumentation\n */\nexport interface LoggingConfig {\n /** Enable trace context in logs */\n enabled: boolean;\n /** Include trace ID in logs */\n includeTraceId?: boolean;\n /** Include span ID in logs */\n includeSpanId?: boolean;\n /** Include trace flags in logs */\n includeTraceFlags?: boolean;\n /** Log level for instrumentation messages */\n level?: 'debug' | 'info' | 'warn' | 'error';\n}\n\n/**\n * GraphQL instrumentation configuration\n */\nexport interface GraphQLInstrumentationConfig {\n /** Enable GraphQL instrumentation */\n enabled: boolean;\n /** Include query/mutation in span attributes */\n includeDocument?: boolean;\n /** Include variables in span attributes (be careful with sensitive data) */\n includeVariables?: boolean;\n /** Include result in span attributes */\n includeResult?: boolean;\n /** Depth to which to serialize document */\n documentDepth?: number;\n /** Operations to ignore */\n ignoredOperations?: string[];\n /** Include resolver-level spans */\n includeResolvers?: boolean;\n /** Max depth for resolver spans */\n resolverSpanDepth?: number;\n /**\n * Explicit allowlist of GraphQL operation names permitted as `operation_name`\n * metric labels. Any operation not in this list is bucketed to `'other'`.\n * When omitted, client-controlled operation names are bucketed to `'named'`\n * (or `'anonymous'`) so untrusted input cannot explode metric cardinality.\n */\n allowedMetricOperationNames?: string[];\n /**\n * Opt in to tracking observed GraphQL operation names dynamically up to\n * {@link maxOperationNameCardinality} when no explicit allowlist is set.\n * Defaults to `false` (fail-closed against cardinality exhaustion).\n */\n includeOperationNameInMetrics?: boolean;\n /** Maximum distinct operation_name labels tracked when dynamic tracking is enabled (default: 100) */\n maxOperationNameCardinality?: number;\n}\n\n/**\n * Database instrumentation configuration\n */\nexport interface DatabaseInstrumentationConfig {\n /** Enable database instrumentation */\n enabled: boolean;\n /** Include SQL query in span attributes */\n includeStatement?: boolean;\n /** Include query parameters (be careful with sensitive data) */\n includeParameters?: boolean;\n /** Include row count in span attributes */\n includeRowCount?: boolean;\n /** Slow query threshold in ms (logs warning if exceeded) */\n slowQueryThreshold?: number;\n /** Operations to ignore */\n ignoredOperations?: string[];\n}\n\n/**\n * HTTP instrumentation configuration\n */\nexport interface HTTPInstrumentationConfig {\n /** Enable HTTP instrumentation */\n enabled: boolean;\n /** Include request headers */\n includeRequestHeaders?: boolean;\n /** Include response headers */\n includeResponseHeaders?: boolean;\n /** Include request body (be careful with sensitive data) */\n includeRequestBody?: boolean;\n /** Include response body */\n includeResponseBody?: boolean;\n /** Headers to redact */\n redactedHeaders?: string[];\n /** Routes to ignore */\n ignoredRoutes?: string[];\n /** Request size threshold for body inclusion */\n maxBodySize?: number;\n}\n\n/**\n * Cache instrumentation configuration\n */\nexport interface CacheInstrumentationConfig {\n /** Enable cache instrumentation */\n enabled: boolean;\n /** Include cache key in span attributes */\n includeKey?: boolean;\n /** Include cache value size */\n includeValueSize?: boolean;\n /** Include TTL in span attributes */\n includeTTL?: boolean;\n}\n\n/**\n * Event queue instrumentation configuration\n */\nexport interface EventQueueInstrumentationConfig {\n /** Enable event queue instrumentation */\n enabled: boolean;\n /** Include message payload (be careful with sensitive data) */\n includePayload?: boolean;\n /** Include message headers */\n includeHeaders?: boolean;\n /** Max payload size to include */\n maxPayloadSize?: number;\n}\n\n/**\n * Complete instrumentation configuration\n */\nexport interface InstrumentationConfig {\n /** Enable all instrumentation (master switch) */\n enabled: boolean;\n /** Feature flags for conditional enable/disable */\n features: InstrumentationFeatureFlags;\n /** Tracing configuration */\n tracing: TracingConfig;\n /** Metrics configuration */\n metrics: MetricsConfig;\n /** Logging configuration */\n logging: LoggingConfig;\n /** GraphQL instrumentation configuration */\n graphql: GraphQLInstrumentationConfig;\n /** Database instrumentation configuration */\n database: DatabaseInstrumentationConfig;\n /** HTTP instrumentation configuration */\n http: HTTPInstrumentationConfig;\n /** Cache instrumentation configuration */\n cache: CacheInstrumentationConfig;\n /** Event queue instrumentation configuration */\n eventQueue: EventQueueInstrumentationConfig;\n}\n\n/**\n * Span attributes for consistent naming\n */\nexport interface SpanAttributes {\n /** Service name */\n 'service.name'?: string;\n /** Service version */\n 'service.version'?: string;\n /** Environment */\n 'deployment.environment'?: string;\n /** Operation name */\n 'operation.name'?: string;\n /** Operation type */\n 'operation.type'?: string;\n /** User ID */\n 'user.id'?: string;\n /** Tenant ID */\n 'tenant.id'?: string;\n /** Workspace ID */\n 'workspace.id'?: string;\n /** Request ID */\n 'request.id'?: string;\n /** Error flag */\n error?: boolean;\n /** Error message */\n 'error.message'?: string;\n /** Error type */\n 'error.type'?: string;\n /** Custom attributes */\n [key: string]: string | number | boolean | undefined;\n}\n\n/**\n * Metric types\n */\nexport type MetricType = 'counter' | 'histogram' | 'gauge' | 'upDownCounter';\n\n/**\n * Metric definition\n */\nexport interface MetricDefinition {\n /** Metric name */\n name: string;\n /** Metric description */\n description: string;\n /** Metric type */\n type: MetricType;\n /** Unit of measurement */\n unit?: string;\n /** Label keys */\n labelKeys?: string[];\n /** Histogram boundaries (for histogram type) */\n boundaries?: number[];\n}\n\n/**\n * Predefined metrics for microservices\n */\nexport const STANDARD_METRICS: Record<string, MetricDefinition> = {\n // HTTP metrics\n HTTP_REQUEST_DURATION: {\n name: 'http_request_duration_ms',\n description: 'HTTP request duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['method', 'route', 'status_code'],\n boundaries: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],\n },\n HTTP_REQUEST_TOTAL: {\n name: 'http_requests_total',\n description: 'Total number of HTTP requests',\n type: 'counter',\n labelKeys: ['method', 'route', 'status_code'],\n },\n HTTP_REQUEST_SIZE: {\n name: 'http_request_size_bytes',\n description: 'HTTP request size in bytes',\n type: 'histogram',\n unit: 'bytes',\n labelKeys: ['method', 'route'],\n boundaries: [100, 1000, 10000, 100000, 1000000],\n },\n HTTP_RESPONSE_SIZE: {\n name: 'http_response_size_bytes',\n description: 'HTTP response size in bytes',\n type: 'histogram',\n unit: 'bytes',\n labelKeys: ['method', 'route'],\n boundaries: [100, 1000, 10000, 100000, 1000000],\n },\n\n // GraphQL metrics\n GRAPHQL_OPERATION_DURATION: {\n name: 'graphql_operation_duration_ms',\n description: 'GraphQL operation duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['operation_type', 'operation_name'],\n boundaries: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000],\n },\n GRAPHQL_OPERATION_TOTAL: {\n name: 'graphql_operations_total',\n description: 'Total number of GraphQL operations',\n type: 'counter',\n labelKeys: ['operation_type', 'operation_name', 'status'],\n },\n GRAPHQL_RESOLVER_DURATION: {\n name: 'graphql_resolver_duration_ms',\n description: 'GraphQL resolver duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['type_name', 'field_name'],\n boundaries: [1, 5, 10, 25, 50, 100, 250, 500],\n },\n\n // Database metrics\n DB_QUERY_DURATION: {\n name: 'db_query_duration_ms',\n description: 'Database query duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['operation', 'model'],\n boundaries: [1, 5, 10, 25, 50, 100, 250, 500, 1000],\n },\n DB_QUERY_TOTAL: {\n name: 'db_queries_total',\n description: 'Total number of database queries',\n type: 'counter',\n labelKeys: ['operation', 'model', 'status'],\n },\n DB_CONNECTION_POOL_SIZE: {\n name: 'db_connection_pool_size',\n description: 'Database connection pool size',\n type: 'gauge',\n labelKeys: ['state'],\n },\n\n // Cache metrics\n CACHE_OPERATION_DURATION: {\n name: 'cache_operation_duration_ms',\n description: 'Cache operation duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['operation'],\n boundaries: [0.1, 0.5, 1, 2, 5, 10, 25, 50],\n },\n CACHE_HIT_TOTAL: {\n name: 'cache_hits_total',\n description: 'Total number of cache hits',\n type: 'counter',\n labelKeys: ['cache_type'],\n },\n CACHE_MISS_TOTAL: {\n name: 'cache_misses_total',\n description: 'Total number of cache misses',\n type: 'counter',\n labelKeys: ['cache_type'],\n },\n\n // Business metrics\n OPERATION_DURATION: {\n name: 'operation_duration_ms',\n description: 'Business operation duration in milliseconds',\n type: 'histogram',\n unit: 'ms',\n labelKeys: ['operation', 'status'],\n boundaries: [10, 50, 100, 250, 500, 1000, 2500, 5000, 10000],\n },\n OPERATION_TOTAL: {\n name: 'operations_total',\n description: 'Total number of business operations',\n type: 'counter',\n labelKeys: ['operation', 'status'],\n },\n ACTIVE_OPERATIONS: {\n name: 'active_operations',\n description: 'Number of currently active operations',\n type: 'upDownCounter',\n labelKeys: ['operation'],\n },\n\n // Resource-cap metrics (BOFF-4809)\n RESOURCE_CAPS_PLAN_RESOLUTION: {\n name: 'resource_caps.plan_resolution_total',\n description: 'Total number of billing plan resolutions for resource caps',\n type: 'counter',\n labelKeys: ['result', 'reason'],\n },\n RESOURCE_CAPS_ENFORCEMENT: {\n name: 'resource_caps.enforcement_total',\n description: 'Total number of resource cap enforcement checks',\n type: 'counter',\n labelKeys: ['resource', 'plan_tier', 'result'],\n },\n RESOURCE_CAPS_CLIENTLESS_FALLBACK: {\n name: 'resource_caps.clientless_fallback_total',\n description: 'Total number of times resource caps fell back because no billing source was configured at bootstrap',\n type: 'counter',\n labelKeys: [],\n },\n};\n\n/**\n * Span context for propagation\n */\nexport interface SpanContext {\n traceId: string;\n spanId: string;\n traceFlags: number;\n isRemote?: boolean;\n}\n\n/**\n * Trace context for logging\n */\nexport interface TraceContext {\n traceId?: string;\n spanId?: string;\n traceFlags?: number;\n parentSpanId?: string;\n}\n\n/**\n * Operation context for instrumentation\n */\nexport interface OperationContext {\n /** Operation name */\n operationName: string;\n /** Operation type (query, mutation, subscription, http, db, cache, etc.) */\n operationType: string;\n /** Actor ID */\n actorId?: string;\n /** Tenant ID */\n tenantId?: string;\n /** Workspace ID */\n workspaceId?: string;\n /** Request ID */\n requestId?: string;\n /** Additional attributes */\n attributes?: Record<string, string | number | boolean>;\n}\n","/**\n * GraphQL Instrumentation Plugin\n *\n * Envelop/GraphQL Yoga plugin for comprehensive GraphQL operation\n * instrumentation including tracing, metrics, and logging.\n *\n * Uses Apollo Federation inline trace plugin for automatic resolver/field-level\n * tracing without manual instrumentation code in microservices.\n *\n * @module instrumentation/graphql-plugin\n * @category Observability\n */\n\nimport { createRequire } from 'node:module';\nimport { logger } from '../logger/index.js';\nimport { getInstrumentationConfig, isFeatureEnabled, isInstrumentationConfigInitialized } from './config.js';\nimport { createCounter, createHistogram, type MetricLabels } from './metrics-collector.js';\nimport { getTracer, SpanKind, SpanStatus, type Span } from './tracer.js';\nimport { STANDARD_METRICS } from './types.js';\n\n// Create a require function for loading optional CommonJS modules in ESM context\nconst require = createRequire(import.meta.url);\n\n// ============================================================================\n// Prometheus Metrics Plugin\n// ============================================================================\n\n/**\n * Cached reference to the Prometheus plugin.\n * Uses lazy loading to avoid top-level await (CJS compatibility).\n */\nlet prometheusPluginFactory: ((options: unknown) => unknown) | null | undefined = undefined;\nlet prometheusLoadAttempted = false;\n\n/**\n * Lazily load the Prometheus plugin.\n * Returns null if not available.\n */\nfunction loadPrometheusPlugin(): ((options: unknown) => unknown) | null {\n if (prometheusLoadAttempted) {\n return prometheusPluginFactory ?? null;\n }\n\n prometheusLoadAttempted = true;\n\n try {\n // Use require for synchronous loading of optional peer dependency\n const module = require('@graphql-yoga/plugin-prometheus');\n prometheusPluginFactory = module.usePrometheus;\n if (prometheusPluginFactory) {\n logger.info('[Instrumentation] Successfully loaded @graphql-yoga/plugin-prometheus');\n } else {\n logger.warn('[Instrumentation] @graphql-yoga/plugin-prometheus loaded but usePrometheus not found');\n }\n return prometheusPluginFactory ?? null;\n } catch (error) {\n // Plugin not installed\n logger.warn('[Instrumentation] Failed to load @graphql-yoga/plugin-prometheus:', error);\n prometheusPluginFactory = null;\n return null;\n }\n}\n\n/**\n * Options for the Prometheus metrics plugin\n */\nexport interface PrometheusPluginOptions {\n /** Endpoint to expose metrics (default: '/metrics') */\n endpoint?: string | false;\n /** Skip introspection queries from metrics (default: true) */\n skipIntrospection?: boolean;\n /** Enable HTTP duration metrics (default: true) */\n httpDuration?: boolean;\n /** Enable request duration histogram (default: true) */\n requestDuration?: boolean;\n /** Enable request count metrics (default: true) */\n requestCount?: boolean;\n /** Enable error count metrics (default: true) */\n errorCount?: boolean;\n /** Enable resolver-level metrics (default: false - has performance overhead) */\n resolverMetrics?: boolean;\n /** Specific resolvers to instrument (e.g., ['Query.*', 'Mutation.*']) */\n instrumentResolvers?: string[];\n /** Enable deprecated field tracking (default: true) */\n deprecatedFields?: boolean;\n /** Enable parse phase metrics (default: true) */\n parsePhase?: boolean;\n /** Enable validate phase metrics (default: true) */\n validatePhase?: boolean;\n /** Enable context phase metrics (default: true) */\n contextPhase?: boolean;\n /** Enable execute phase metrics (default: true) */\n executePhase?: boolean;\n}\n\n/**\n * Create the Prometheus metrics plugin for automatic GraphQL metrics.\n *\n * This plugin automatically tracks all GraphQL operations and provides\n * Prometheus-compatible metrics for monitoring dashboards.\n *\n * Metrics exposed:\n * - graphql_yoga_http_duration - HTTP request duration\n * - graphql_envelop_request_duration - Operation duration histogram\n * - graphql_envelop_request - Operation counter\n * - graphql_envelop_error_result - Error counter\n * - graphql_envelop_deprecated_field - Deprecated field usage\n * - graphql_envelop_phase_* - Execution phase metrics\n * - graphql_envelop_execute_resolver - Resolver metrics (if enabled)\n *\n * @example\n * ```typescript\n * import { createPrometheusPlugin } from '@burdenoff/be-sdk/instrumentation';\n *\n * const yoga = createYoga({\n * plugins: [\n * createPrometheusPlugin({\n * endpoint: '/metrics',\n * resolverMetrics: false,\n * }),\n * ],\n * });\n * ```\n */\nexport function createPrometheusPlugin(options?: PrometheusPluginOptions): unknown | null {\n // Check if metrics is enabled\n if (isInstrumentationConfigInitialized() && !isFeatureEnabled('metrics')) {\n logger.debug('[Instrumentation] Metrics disabled, skipping Prometheus plugin');\n return null;\n }\n\n // Lazily load the plugin\n const pluginFactory = loadPrometheusPlugin();\n\n // Check if the plugin is available\n if (!pluginFactory) {\n logger.debug('[Instrumentation] @graphql-yoga/plugin-prometheus not installed, metrics not available');\n return null;\n }\n\n const config = {\n // Expose metrics endpoint (set to false to disable, e.g., for push mode)\n endpoint: options?.endpoint ?? '/metrics',\n // Skip introspection queries from metrics\n skipIntrospection: options?.skipIntrospection ?? true,\n // Metrics configuration\n metrics: {\n // HTTP-level metrics\n graphql_yoga_http_duration: options?.httpDuration ?? true,\n // Operation-level metrics\n graphql_envelop_request_duration: options?.requestDuration ?? true,\n graphql_envelop_request_time_summary: options?.requestDuration ?? true,\n graphql_envelop_request: options?.requestCount ?? true,\n graphql_envelop_error_result: options?.errorCount ?? true,\n graphql_envelop_deprecated_field: options?.deprecatedFields ?? true,\n // Execution phase metrics\n graphql_envelop_phase_parse: options?.parsePhase ?? true,\n graphql_envelop_phase_validate: options?.validatePhase ?? true,\n graphql_envelop_phase_context: options?.contextPhase ?? true,\n graphql_envelop_phase_execute: options?.executePhase ?? true,\n graphql_envelop_phase_subscribe: true,\n // Schema change tracking\n graphql_envelop_schema_change: true,\n // Resolver-level metrics (disabled by default due to performance overhead)\n graphql_envelop_execute_resolver: options?.resolverMetrics ?? false,\n },\n // If resolver metrics enabled, optionally filter which resolvers to instrument\n ...(options?.instrumentResolvers && { instrumentResolvers: options.instrumentResolvers }),\n };\n\n logger.debug('[Instrumentation] Using Prometheus metrics plugin', {\n endpoint: config.endpoint,\n resolverMetrics: options?.resolverMetrics ?? false,\n });\n\n return pluginFactory(config);\n}\n\n/**\n * Check if Prometheus plugin is available\n */\nexport function isPrometheusAvailable(): boolean {\n return loadPrometheusPlugin() !== null;\n}\n\n// ============================================================================\n// Apollo Federation Inline Trace Plugin\n// ============================================================================\n\n/**\n * Cached reference to the Apollo inline trace plugin.\n * Uses lazy loading to avoid top-level await (CJS compatibility).\n */\nlet apolloInlineTracePluginFactory: (() => unknown) | null | undefined = undefined;\nlet apolloInlineTraceLoadAttempted = false;\n\n/**\n * Lazily load the Apollo inline trace plugin.\n * Returns null if not available.\n */\nfunction loadApolloInlineTracePlugin(): (() => unknown) | null {\n if (apolloInlineTraceLoadAttempted) {\n return apolloInlineTracePluginFactory ?? null;\n }\n\n apolloInlineTraceLoadAttempted = true;\n\n try {\n // Use require for synchronous loading of optional peer dependency\n const module = require('@graphql-yoga/plugin-apollo-inline-trace');\n apolloInlineTracePluginFactory = module.useApolloInlineTrace;\n return apolloInlineTracePluginFactory ?? null;\n } catch {\n // Plugin not installed\n apolloInlineTracePluginFactory = null;\n return null;\n }\n}\n\n/**\n * Options for the Apollo Federation inline trace plugin\n */\nexport interface ApolloInlineTraceOptions {\n /** Include detailed field-level traces (default: true) */\n includeFieldTraces?: boolean;\n /** Include variable values in traces (default: false for security) */\n includeVariables?: boolean;\n /** Operations to exclude from tracing */\n excludeOperations?: string[];\n}\n\n/**\n * Create the Apollo Federation inline trace plugin for automatic tracing.\n *\n * This plugin automatically instruments all GraphQL operations and resolvers\n * without requiring manual tracing code. It's designed to work with Apollo Federation\n * and the API Gateway for distributed tracing.\n *\n * @example\n * ```typescript\n * import { createApolloInlineTracePlugin } from '@burdenoff/be-sdk/instrumentation';\n *\n * const yoga = createYoga({\n * plugins: [\n * createApolloInlineTracePlugin(),\n * ],\n * });\n * ```\n */\nexport function createApolloInlineTracePlugin(_options?: ApolloInlineTraceOptions): unknown | null {\n // Check if tracing is enabled\n if (isInstrumentationConfigInitialized() && !isFeatureEnabled('tracing')) {\n logger.debug('[Instrumentation] Tracing disabled, skipping Apollo inline trace plugin');\n return null;\n }\n\n // Lazily load the plugin\n const pluginFactory = loadApolloInlineTracePlugin();\n\n // Check if the plugin is available\n if (!pluginFactory) {\n logger.debug('[Instrumentation] @graphql-yoga/plugin-apollo-inline-trace not installed, using fallback tracing');\n return null;\n }\n\n logger.debug('[Instrumentation] Using Apollo Federation inline trace plugin');\n return pluginFactory();\n}\n\n/**\n * Check if Apollo inline tracing is available\n */\nexport function isApolloInlineTraceAvailable(): boolean {\n return loadApolloInlineTracePlugin() !== null;\n}\n\n/**\n * GraphQL operation type\n */\nexport type GraphQLOperationType = 'query' | 'mutation' | 'subscription';\n\n/**\n * GraphQL operation info\n */\nexport interface GraphQLOperationInfo {\n operationType: GraphQLOperationType;\n operationName: string | null;\n document?: string;\n variables?: Record<string, unknown>;\n}\n\n/**\n * Context extension for instrumentation\n */\nexport interface InstrumentationContextExtension {\n _instrumentation?: {\n span?: Span;\n startTime?: number;\n operationInfo?: GraphQLOperationInfo;\n };\n}\n\n/**\n * Create GraphQL metrics\n */\nfunction createGraphQLMetrics(): {\n operationDuration: ReturnType<typeof createHistogram>;\n operationTotal: ReturnType<typeof createCounter>;\n operationErrors: ReturnType<typeof createCounter>;\n resolverDuration: ReturnType<typeof createHistogram>;\n resolverTotal: ReturnType<typeof createCounter>;\n} {\n const def = STANDARD_METRICS;\n\n return {\n operationDuration: createHistogram(\n def['GRAPHQL_OPERATION_DURATION']?.name || 'graphql_operation_duration_ms',\n def['GRAPHQL_OPERATION_DURATION']?.description || 'GraphQL operation duration',\n def['GRAPHQL_OPERATION_DURATION']?.boundaries\n ),\n operationTotal: createCounter(\n def['GRAPHQL_OPERATION_TOTAL']?.name || 'graphql_operations_total',\n def['GRAPHQL_OPERATION_TOTAL']?.description || 'Total GraphQL operations'\n ),\n operationErrors: createCounter('graphql_operation_errors_total', 'Total GraphQL operation errors'),\n resolverDuration: createHistogram(\n def['GRAPHQL_RESOLVER_DURATION']?.name || 'graphql_resolver_duration_ms',\n def['GRAPHQL_RESOLVER_DURATION']?.description || 'GraphQL resolver duration',\n def['GRAPHQL_RESOLVER_DURATION']?.boundaries\n ),\n resolverTotal: createCounter('graphql_resolvers_total', 'Total GraphQL resolver calls'),\n };\n}\n\n// Lazy-initialized metrics\nlet graphqlMetrics: ReturnType<typeof createGraphQLMetrics> | null = null;\n\nfunction getGraphQLMetrics(): ReturnType<typeof createGraphQLMetrics> {\n if (!graphqlMetrics) {\n graphqlMetrics = createGraphQLMetrics();\n }\n return graphqlMetrics;\n}\n\n/** Reset cached GraphQL metric handles (for tests after resetting the metrics registry). */\nexport function resetGraphQLMetricsForTests(): void {\n graphqlMetrics = null;\n}\n\nconst VALID_GRAPHQL_OP_NAME_RE = /^[A-Za-z_]\\w{0,63}$/;\n\nexport interface OperationNameLabelOptions {\n /** Explicit allowlist of permitted `operation_name` metric label values. */\n allowedOperationNames?: readonly string[];\n /**\n * When true and no allowlist is configured, allow up to `maxDynamicNames`\n * distinct observed valid GraphQL identifiers before bucketing to `'other'`.\n * Defaults to `false` (bucket all named operations to `'named'`).\n */\n includeOperationNameInMetrics?: boolean;\n /** Cap on dynamically tracked operation names (default: 100). */\n maxDynamicNames?: number;\n}\n\n/**\n * Bound client-controlled GraphQL operation names before using them as metric\n * labels (BOFF-15984).\n *\n * - Missing/empty -> `'anonymous'`\n * - With an explicit allowlist -> exact name if allowlisted, else `'other'`\n * - Without an allowlist and `includeOperationNameInMetrics !== true` -> `'named'`\n * - With `includeOperationNameInMetrics: true` -> valid GraphQL identifier up to\n * `maxDynamicNames` distinct values in `observedNames`, else `'other'`\n */\nexport function normalizeOperationNameForMetric(\n operationName: string | null | undefined,\n options: OperationNameLabelOptions = {},\n observedNames?: Set<string>\n): string {\n const trimmed = operationName?.trim();\n if (!trimmed) return 'anonymous';\n\n if (options.allowedOperationNames && options.allowedOperationNames.length > 0) {\n return options.allowedOperationNames.includes(trimmed) ? trimmed : 'other';\n }\n\n if (!options.includeOperationNameInMetrics) {\n return 'named';\n }\n\n if (!VALID_GRAPHQL_OP_NAME_RE.test(trimmed)) {\n return 'other';\n }\n\n const cap = Math.max(1, Math.floor(options.maxDynamicNames ?? 100));\n if (observedNames) {\n if (observedNames.has(trimmed)) return trimmed;\n if (observedNames.size >= cap) return 'other';\n observedNames.add(trimmed);\n return trimmed;\n }\n return 'named';\n}\n\n/**\n * Extract operation info from GraphQL execution args\n */\nexport function extractOperationInfo(args: {\n document?: { loc?: { source?: { body?: string } }; definitions?: unknown[] };\n operationName?: string | null;\n variableValues?: Record<string, unknown>;\n}): GraphQLOperationInfo {\n let operationType: GraphQLOperationType = 'query';\n let operationName: string | null = args.operationName || null;\n\n // Try to extract operation type from document\n const definitions = args.document?.definitions as\n Array<{ kind?: string; operation?: string; name?: { value?: string } }> | undefined;\n if (definitions && definitions.length > 0) {\n for (const def of definitions) {\n if (def.kind === 'OperationDefinition') {\n operationType = (def.operation as GraphQLOperationType) || 'query';\n if (!operationName && def.name?.value) {\n operationName = def.name.value;\n }\n break;\n }\n }\n }\n\n return {\n operationType,\n operationName,\n document: args.document?.loc?.source?.body,\n variables: args.variableValues,\n };\n}\n\n/**\n * Check if operation should be ignored\n */\nfunction shouldIgnoreOperation(operationName: string | null): boolean {\n if (!isInstrumentationConfigInitialized()) return false;\n\n const config = getInstrumentationConfig();\n const ignoredOps = config.graphql.ignoredOperations || [];\n\n return operationName ? ignoredOps.includes(operationName) : false;\n}\n\n/**\n * GraphQL Yoga plugin for instrumentation\n *\n * @example\n * ```typescript\n * import { createYoga } from 'graphql-yoga';\n * import { createGraphQLInstrumentationPlugin } from '@burdenoff/be-sdk/instrumentation';\n *\n * const yoga = createYoga({\n * plugins: [\n * createGraphQLInstrumentationPlugin(),\n * ],\n * });\n * ```\n */\nexport function createGraphQLInstrumentationPlugin(options?: OperationNameLabelOptions): {\n onExecute: (args: {\n args: {\n document?: unknown;\n operationName?: string | null;\n variableValues?: Record<string, unknown>;\n contextValue?: unknown;\n };\n }) =>\n | {\n onExecuteDone: (args: { result: unknown; setResult?: (result: unknown) => void }) => void;\n }\n | undefined;\n onSubscribe?: (args: { args: unknown }) => void;\n} {\n const observedOperationNames = new Set<string>();\n\n return {\n onExecute({\n args,\n }): { onExecuteDone: (args: { result: unknown; setResult?: (result: unknown) => void }) => void } | undefined {\n // Check if GraphQL instrumentation is enabled\n if (!isFeatureEnabled('graphql')) {\n return undefined;\n }\n\n const operationInfo = extractOperationInfo(\n args as {\n document?: { loc?: { source?: { body?: string } }; definitions?: unknown[] };\n operationName?: string | null;\n variableValues?: Record<string, unknown>;\n }\n );\n\n // Check if this operation should be ignored\n if (shouldIgnoreOperation(operationInfo.operationName)) {\n return undefined;\n }\n\n const startTime = Date.now();\n const config = getInstrumentationConfig();\n const metrics = getGraphQLMetrics();\n\n // Start span for tracing\n let span: Span | undefined;\n if (isFeatureEnabled('tracing')) {\n const tracer = getTracer();\n const spanName = operationInfo.operationName\n ? `GraphQL ${operationInfo.operationType} ${operationInfo.operationName}`\n : `GraphQL ${operationInfo.operationType}`;\n\n span = tracer.startSpan(spanName, SpanKind.SERVER);\n\n span.setAttributes({\n 'graphql.operation.type': operationInfo.operationType,\n 'graphql.operation.name': operationInfo.operationName || 'anonymous',\n });\n\n // Include document if configured\n if (config.graphql.includeDocument && operationInfo.document) {\n span.setAttribute('graphql.document', operationInfo.document.substring(0, 2000));\n }\n\n // Include variables if configured (be careful with sensitive data)\n if (config.graphql.includeVariables && operationInfo.variables) {\n try {\n span.setAttribute('graphql.variables', JSON.stringify(operationInfo.variables).substring(0, 500));\n } catch {\n // Ignore serialization errors\n }\n }\n }\n\n // Log operation start\n if (isFeatureEnabled('logging')) {\n logger.debug('[GraphQL] Operation started', {\n type: operationInfo.operationType,\n name: operationInfo.operationName || 'anonymous',\n });\n }\n\n // Store instrumentation context\n const context = args.contextValue as InstrumentationContextExtension | undefined;\n if (context) {\n context._instrumentation = {\n span,\n startTime,\n operationInfo,\n };\n }\n\n return {\n onExecuteDone({ result }): void {\n const duration = Date.now() - startTime;\n const hasErrors =\n result &&\n typeof result === 'object' &&\n 'errors' in result &&\n Array.isArray((result as { errors?: unknown[] }).errors) &&\n (result as { errors: unknown[] }).errors.length > 0;\n\n // Record metrics with bounded operation_name cardinality (BOFF-15984)\n if (isFeatureEnabled('metrics')) {\n const metricOperationName = normalizeOperationNameForMetric(\n operationInfo.operationName,\n {\n allowedOperationNames: options?.allowedOperationNames ?? config.graphql.allowedMetricOperationNames,\n includeOperationNameInMetrics:\n options?.includeOperationNameInMetrics ?? config.graphql.includeOperationNameInMetrics,\n maxDynamicNames: options?.maxDynamicNames ?? config.graphql.maxOperationNameCardinality,\n },\n observedOperationNames\n );\n const labels: MetricLabels = {\n operation_type: operationInfo.operationType,\n operation_name: metricOperationName,\n };\n\n metrics.operationDuration.record(duration, labels);\n metrics.operationTotal.inc({ ...labels, status: hasErrors ? 'error' : 'success' });\n\n if (hasErrors) {\n metrics.operationErrors.inc(labels);\n }\n }\n\n // Update span\n if (span) {\n span.setAttribute('graphql.duration_ms', duration);\n\n if (hasErrors) {\n span.setStatus(SpanStatus.ERROR, 'GraphQL operation had errors');\n const errors = (result as { errors?: Array<{ message?: string }> }).errors;\n if (errors && errors.length > 0) {\n span.setAttribute('graphql.error_count', errors.length);\n span.addEvent('graphql.errors', {\n errors: errors.map((e) => e.message || 'Unknown error').join('; '),\n });\n }\n } else {\n span.setStatus(SpanStatus.OK);\n }\n\n // Include result if configured\n if (config.graphql.includeResult) {\n try {\n span.setAttribute('graphql.result', JSON.stringify(result).substring(0, 500));\n } catch {\n // Ignore\n }\n }\n\n span.end();\n }\n\n // Log completion\n if (isFeatureEnabled('logging')) {\n if (hasErrors) {\n logger.warn('[GraphQL] Operation completed with errors', {\n type: operationInfo.operationType,\n name: operationInfo.operationName || 'anonymous',\n duration: `${duration}ms`,\n errorCount: ((result as { errors?: unknown[] }).errors || []).length,\n });\n } else {\n logger.debug('[GraphQL] Operation completed', {\n type: operationInfo.operationType,\n name: operationInfo.operationName || 'anonymous',\n duration: `${duration}ms`,\n });\n }\n }\n },\n };\n },\n };\n}\n\n/**\n * Resolver instrumentation wrapper\n *\n * Use this to wrap individual resolvers for detailed tracing and metrics.\n *\n * @example\n * ```typescript\n * const resolvers = {\n * Query: {\n * getUser: instrumentResolver('Query.getUser', async (parent, args, context) => {\n * // resolver logic\n * }),\n * },\n * };\n * ```\n */\nexport function instrumentResolver<TArgs extends unknown[], TResult>(\n name: string,\n resolver: (...args: TArgs) => Promise<TResult>,\n options?: {\n /** Include resolver arguments in span */\n includeArgs?: boolean;\n /** Include resolver result in span */\n includeResult?: boolean;\n /** Custom span attributes */\n attributes?: Record<string, string | number | boolean>;\n }\n): (...args: TArgs) => Promise<TResult> {\n const [typeName, fieldName] = name.includes('.') ? name.split('.', 2) : ['Unknown', name];\n\n return async (...args: TArgs): Promise<TResult> => {\n // Check if GraphQL instrumentation is enabled\n if (!isFeatureEnabled('graphql')) {\n return resolver(...args);\n }\n\n const config = getInstrumentationConfig();\n\n // Check resolver depth limit\n // (This is a simplified check - in production you'd track nesting level)\n const startTime = Date.now();\n const metrics = getGraphQLMetrics();\n\n // Start span\n let span: Span | undefined;\n if (isFeatureEnabled('tracing') && config.graphql.includeResolvers) {\n const tracer = getTracer();\n span = tracer.startSpan(`Resolver: ${name}`, SpanKind.INTERNAL);\n\n span.setAttributes({\n 'graphql.resolver.type': typeName || 'Unknown',\n 'graphql.resolver.field': fieldName || name,\n ...options?.attributes,\n });\n\n if (options?.includeArgs && args.length > 1) {\n try {\n // args[1] is typically the resolver arguments\n span.setAttribute('graphql.resolver.args', JSON.stringify(args[1]).substring(0, 500));\n } catch {\n // Ignore\n }\n }\n }\n\n try {\n const result = await resolver(...args);\n\n if (span) {\n span.setStatus(SpanStatus.OK);\n if (options?.includeResult) {\n try {\n span.setAttribute('graphql.resolver.result', JSON.stringify(result).substring(0, 500));\n } catch {\n // Ignore\n }\n }\n }\n\n return result;\n } catch (error) {\n if (span && error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n const duration = Date.now() - startTime;\n\n if (span) {\n span.end();\n }\n\n // Record metrics\n if (isFeatureEnabled('metrics')) {\n metrics.resolverDuration.record(duration, {\n type_name: typeName || 'Unknown',\n field_name: fieldName || name,\n });\n metrics.resolverTotal.inc({\n type_name: typeName || 'Unknown',\n field_name: fieldName || name,\n });\n }\n }\n };\n}\n\n/**\n * Create instrumented resolvers from a resolver map\n *\n * @example\n * ```typescript\n * const resolvers = instrumentResolverMap({\n * Query: {\n * getUser: async (parent, args, context) => { ... },\n * getUsers: async (parent, args, context) => { ... },\n * },\n * Mutation: {\n * createUser: async (parent, args, context) => { ... },\n * },\n * });\n * ```\n */\nexport function instrumentResolverMap<\n T extends Record<string, Record<string, (...args: unknown[]) => Promise<unknown>>>,\n>(\n resolverMap: T,\n options?: {\n /** Types to include (default: all) */\n includeTypes?: string[];\n /** Types to exclude */\n excludeTypes?: string[];\n /** Fields to exclude (format: \"TypeName.fieldName\") */\n excludeFields?: string[];\n }\n): T {\n const result: Record<string, Record<string, (...args: unknown[]) => Promise<unknown>>> = {};\n\n for (const [typeName, fields] of Object.entries(resolverMap)) {\n // Check if type should be included\n if (options?.excludeTypes?.includes(typeName)) {\n result[typeName] = fields;\n continue;\n }\n if (options?.includeTypes && !options.includeTypes.includes(typeName)) {\n result[typeName] = fields;\n continue;\n }\n\n result[typeName] = {};\n\n for (const [fieldName, resolver] of Object.entries(fields)) {\n const fullName = `${typeName}.${fieldName}`;\n\n // Check if field should be excluded\n if (options?.excludeFields?.includes(fullName)) {\n result[typeName][fieldName] = resolver;\n continue;\n }\n\n // Wrap resolver with instrumentation\n result[typeName][fieldName] = instrumentResolver(fullName, resolver);\n }\n }\n\n return result as T;\n}\n\n/**\n * Get current GraphQL operation info from context\n */\nexport function getGraphQLOperationFromContext(context: unknown): GraphQLOperationInfo | undefined {\n const instrumentedContext = context as InstrumentationContextExtension | undefined;\n return instrumentedContext?._instrumentation?.operationInfo;\n}\n\n/**\n * Get current GraphQL span from context\n */\nexport function getGraphQLSpanFromContext(context: unknown): Span | undefined {\n const instrumentedContext = context as InstrumentationContextExtension | undefined;\n return instrumentedContext?._instrumentation?.span;\n}\n","/**\n * Instrumentation Decorators\n *\n * TypeScript decorators for easy method instrumentation with\n * tracing, metrics, and logging.\n *\n * @module instrumentation/decorators\n * @category Observability\n */\n\nimport { logger } from '../logger/index.js';\nimport { isFeatureEnabled } from './config.js';\nimport { createCounter, createHistogram, type MetricLabels } from './metrics-collector.js';\nimport { getTracer, SpanKind, SpanStatus, type Span } from './tracer.js';\n\n/**\n * Type for span attributes (primitive values only)\n */\nexport type SpanAttributes = Record<string, string | number | boolean>;\n\n/**\n * Options for the @Trace decorator\n */\nexport interface TraceOptions {\n /** Custom span name (default: className.methodName) */\n name?: string;\n /** Span kind */\n kind?: SpanKind;\n /** Additional span attributes */\n attributes?: SpanAttributes;\n /** Include method arguments in span (be careful with sensitive data) */\n includeArgs?: boolean;\n /** Include result in span */\n includeResult?: boolean;\n /** Extract attributes from method arguments */\n extractAttributes?: (args: unknown[]) => SpanAttributes;\n /** Skip tracing for this method */\n skip?: boolean | ((args: unknown[]) => boolean);\n}\n\n/**\n * Options for the @Metric decorator\n */\nexport interface MetricOptions {\n /** Custom metric name (default: operation_duration) */\n name?: string;\n /** Additional labels */\n labels?: MetricLabels | ((args: unknown[], result?: unknown) => MetricLabels);\n /** Record count metric */\n recordCount?: boolean;\n /** Record duration metric */\n recordDuration?: boolean;\n /** Custom histogram boundaries */\n boundaries?: number[];\n}\n\n/**\n * Options for the @Log decorator\n */\nexport interface LogOptions {\n /** Log level */\n level?: 'debug' | 'info' | 'warn' | 'error';\n /** Include method arguments */\n includeArgs?: boolean;\n /** Include result */\n includeResult?: boolean;\n /** Log on entry */\n logEntry?: boolean;\n /** Log on exit */\n logExit?: boolean;\n /** Log on error */\n logError?: boolean;\n /** Custom message */\n message?: string;\n}\n\n/**\n * Combined options for the @Instrument decorator\n */\nexport interface InstrumentOptions {\n /** Operation name */\n operationName?: string;\n /** Operation type */\n operationType?: string;\n /** Tracing options */\n trace?: TraceOptions | boolean;\n /** Metrics options */\n metrics?: MetricOptions | boolean;\n /** Logging options */\n log?: LogOptions | boolean;\n /** Skip instrumentation condition */\n skip?: boolean | ((args: unknown[]) => boolean);\n}\n\n/**\n * @Trace decorator - adds tracing to a method\n *\n * @example\n * ```typescript\n * class UserService {\n * @Trace({ name: 'getUserById', kind: SpanKind.INTERNAL })\n * async getUser(id: string): Promise<User> {\n * // ...\n * }\n * }\n * ```\n */\nexport function Trace(options: TraceOptions = {}): MethodDecorator {\n return function <T>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>\n ): TypedPropertyDescriptor<T> {\n const originalMethod = descriptor.value;\n\n if (typeof originalMethod !== 'function') {\n return descriptor;\n }\n\n const className = target.constructor.name;\n const methodName = String(propertyKey);\n const spanName = options.name || `${className}.${methodName}`;\n\n descriptor.value = async function (this: unknown, ...args: unknown[]) {\n // Check if tracing is enabled\n if (!isFeatureEnabled('tracing')) {\n return (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n }\n\n // Check skip condition\n if (options.skip) {\n const shouldSkip = typeof options.skip === 'function' ? options.skip(args) : options.skip;\n if (shouldSkip) {\n return (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n }\n }\n\n const tracer = getTracer();\n const span = tracer.startSpan(spanName, options.kind || SpanKind.INTERNAL);\n\n // Add base attributes\n span.setAttributes({\n 'code.function': methodName,\n 'code.namespace': className,\n ...options.attributes,\n });\n\n // Extract custom attributes from arguments\n if (options.extractAttributes) {\n try {\n const extractedAttrs = options.extractAttributes(args);\n span.setAttributes(extractedAttrs);\n } catch {\n // Ignore extraction errors\n }\n }\n\n // Include args if configured\n if (options.includeArgs) {\n try {\n span.setAttribute('method.args', JSON.stringify(args).substring(0, 1000));\n } catch {\n // Ignore serialization errors\n }\n }\n\n try {\n const result = await (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n\n // Include result if configured\n if (options.includeResult) {\n try {\n span.setAttribute('method.result', JSON.stringify(result).substring(0, 1000));\n } catch {\n // Ignore serialization errors\n }\n }\n\n span.setStatus(SpanStatus.OK);\n return result;\n } catch (error) {\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n } as T;\n\n return descriptor;\n };\n}\n\n/**\n * @Metric decorator - adds metrics to a method\n *\n * @example\n * ```typescript\n * class UserService {\n * @Metric({ name: 'user_fetch', recordCount: true, recordDuration: true })\n * async getUser(id: string): Promise<User> {\n * // ...\n * }\n * }\n * ```\n */\nexport function Metric(options: MetricOptions = {}): MethodDecorator {\n return function <T>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>\n ): TypedPropertyDescriptor<T> {\n const originalMethod = descriptor.value;\n\n if (typeof originalMethod !== 'function') {\n return descriptor;\n }\n\n const className = target.constructor.name;\n const methodName = String(propertyKey);\n const baseName = options.name || `${className.toLowerCase()}_${methodName.toLowerCase()}`;\n\n // Create metrics (they will be no-ops if metrics are disabled)\n const durationHistogram = createHistogram(\n `${baseName}_duration_ms`,\n `Duration of ${className}.${methodName} in milliseconds`,\n options.boundaries\n );\n const totalCounter = createCounter(`${baseName}_total`, `Total calls to ${className}.${methodName}`);\n const errorCounter = createCounter(`${baseName}_errors_total`, `Total errors in ${className}.${methodName}`);\n\n descriptor.value = async function (this: unknown, ...args: unknown[]) {\n // Check if metrics are enabled\n if (!isFeatureEnabled('metrics')) {\n return (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n }\n\n const startTime = Date.now();\n let result: unknown;\n let hasError = false;\n\n try {\n result = await (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n return result;\n } catch (error) {\n hasError = true;\n throw error;\n } finally {\n const duration = Date.now() - startTime;\n\n // Get labels\n let labels: MetricLabels = {};\n if (options.labels) {\n labels = typeof options.labels === 'function' ? options.labels(args, result) : options.labels;\n }\n\n // Record metrics\n if (options.recordDuration !== false) {\n durationHistogram.record(duration, labels);\n }\n\n if (options.recordCount !== false) {\n totalCounter.inc({ ...labels, status: hasError ? 'error' : 'success' });\n }\n\n if (hasError) {\n errorCounter.inc(labels);\n }\n }\n } as T;\n\n return descriptor;\n };\n}\n\n/**\n * @Log decorator - adds logging to a method\n *\n * @example\n * ```typescript\n * class UserService {\n * @Log({ level: 'info', logEntry: true, logExit: true })\n * async getUser(id: string): Promise<User> {\n * // ...\n * }\n * }\n * ```\n */\nexport function Log(options: LogOptions = {}): MethodDecorator {\n return function <T>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>\n ): TypedPropertyDescriptor<T> {\n const originalMethod = descriptor.value;\n\n if (typeof originalMethod !== 'function') {\n return descriptor;\n }\n\n const className = target.constructor.name;\n const methodName = String(propertyKey);\n const level = options.level || 'debug';\n const logEntry = options.logEntry !== false;\n const logExit = options.logExit !== false;\n const logError = options.logError !== false;\n\n descriptor.value = async function (this: unknown, ...args: unknown[]) {\n // Check if logging instrumentation is enabled\n if (!isFeatureEnabled('logging')) {\n return (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n }\n\n const baseMessage = options.message || `${className}.${methodName}`;\n\n // Log entry\n if (logEntry) {\n const entryData: Record<string, unknown> = {\n class: className,\n method: methodName,\n };\n if (options.includeArgs) {\n entryData['args'] = args;\n }\n logger[level](`[Enter] ${baseMessage}`, entryData);\n }\n\n const startTime = Date.now();\n\n try {\n const result = await (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n\n // Log exit\n if (logExit) {\n const duration = Date.now() - startTime;\n const exitData: Record<string, unknown> = {\n class: className,\n method: methodName,\n duration: `${duration}ms`,\n };\n if (options.includeResult) {\n exitData['result'] = result;\n }\n logger[level](`[Exit] ${baseMessage}`, exitData);\n }\n\n return result;\n } catch (error) {\n // Log error\n if (logError) {\n const duration = Date.now() - startTime;\n logger.error(`[Error] ${baseMessage}`, {\n class: className,\n method: methodName,\n duration: `${duration}ms`,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n throw error;\n }\n } as T;\n\n return descriptor;\n };\n}\n\n/**\n * Helper: Check if instrumentation should be skipped\n */\nfunction shouldSkipInstrumentation(\n skipOption: boolean | ((args: unknown[]) => boolean) | undefined,\n args: unknown[]\n): boolean {\n if (!skipOption) {\n return false;\n }\n return typeof skipOption === 'function' ? skipOption(args) : skipOption;\n}\n\n/**\n * Helper: Start and configure tracing span\n */\nfunction startInstrumentationSpan(\n traceOpts: Record<string, unknown> | null,\n operationName: string,\n operationType: string,\n methodName: string,\n className: string,\n args: unknown[]\n): Span | null {\n if (traceOpts === null || !isFeatureEnabled('tracing')) {\n return null;\n }\n\n const tracer = getTracer();\n const span = tracer.startSpan(\n (traceOpts?.['name'] as string | undefined) || operationName,\n (traceOpts?.['kind'] as SpanKind | undefined) || SpanKind.INTERNAL\n );\n\n span.setAttributes({\n 'operation.type': operationType,\n 'code.function': methodName,\n 'code.namespace': className,\n ...(traceOpts?.['attributes'] as SpanAttributes | undefined),\n });\n\n if (traceOpts?.['extractAttributes']) {\n try {\n const extractFn = traceOpts['extractAttributes'] as (args: unknown[]) => SpanAttributes;\n span.setAttributes(extractFn(args));\n } catch {\n // Ignore extraction errors\n }\n }\n\n return span;\n}\n\n/**\n * Helper: Log method entry\n */\nfunction logInstrumentationEntry(\n logOpts: Record<string, unknown> | null,\n operationName: string,\n operationType: string,\n args: unknown[]\n): void {\n if (logOpts === null || !isFeatureEnabled('logging')) {\n return;\n }\n\n if (logOpts?.['logEntry'] === false) {\n return;\n }\n\n const level = (logOpts?.['level'] as 'debug' | 'info' | 'warn' | 'error' | undefined) || 'debug';\n logger[level](`[Enter] ${operationName}`, {\n operation: operationName,\n type: operationType,\n ...(logOpts?.['includeArgs'] ? { args } : {}),\n });\n}\n\n/**\n * Helper: Handle successful method execution\n */\nfunction handleInstrumentationSuccess(\n span: Span | null,\n traceOpts: Record<string, unknown> | null,\n result: unknown\n): void {\n if (!span) {\n return;\n }\n\n span.setStatus(SpanStatus.OK);\n\n if (traceOpts?.['includeResult']) {\n try {\n span.setAttribute('result', JSON.stringify(result).substring(0, 500));\n } catch {\n // Ignore serialization errors\n }\n }\n}\n\n/**\n * Helper: Handle method error\n */\nfunction handleInstrumentationError(\n span: Span | null,\n logOpts: Record<string, unknown> | null,\n operationName: string,\n operationType: string,\n error: unknown,\n startTime: number\n): void {\n if (span && error instanceof Error) {\n span.recordException(error);\n }\n\n if (logOpts !== null && isFeatureEnabled('logging') && logOpts?.['logError'] !== false) {\n logger.error(`[Error] ${operationName}`, {\n operation: operationName,\n type: operationType,\n error: error instanceof Error ? error.message : String(error),\n duration: `${Date.now() - startTime}ms`,\n });\n }\n}\n\n/**\n * Helper: Record metrics in finally block\n */\nfunction recordInstrumentationMetrics(\n metricOpts: Record<string, unknown> | null,\n durationHistogram: ReturnType<typeof createHistogram> | null,\n totalCounter: ReturnType<typeof createCounter> | null,\n errorCounter: ReturnType<typeof createCounter> | null,\n duration: number,\n args: unknown[],\n result: unknown,\n hasError: boolean\n): void {\n if (metricOpts === null || !isFeatureEnabled('metrics')) {\n return;\n }\n\n const labelsFn = metricOpts?.['labels'] as ((args: unknown[], result?: unknown) => MetricLabels) | undefined;\n const labelsObj = metricOpts?.['labels'] as MetricLabels | undefined;\n const labels = typeof metricOpts?.['labels'] === 'function' ? labelsFn?.(args, result) : labelsObj || {};\n\n if (durationHistogram && metricOpts?.['recordDuration'] !== false) {\n durationHistogram.record(duration, labels);\n }\n\n if (totalCounter && metricOpts?.['recordCount'] !== false) {\n totalCounter.inc({ ...labels, status: hasError ? 'error' : 'success' });\n }\n\n if (errorCounter && hasError) {\n errorCounter.inc(labels);\n }\n}\n\n/**\n * Helper: Log method exit in finally block\n */\nfunction logInstrumentationExit(\n logOpts: Record<string, unknown> | null,\n operationName: string,\n operationType: string,\n duration: number,\n result: unknown,\n hasError: boolean\n): void {\n if (logOpts === null || !isFeatureEnabled('logging')) {\n return;\n }\n\n if (logOpts?.['logExit'] === false || hasError) {\n return;\n }\n\n const level = (logOpts?.['level'] as 'debug' | 'info' | 'warn' | 'error' | undefined) || 'debug';\n logger[level](`[Exit] ${operationName}`, {\n operation: operationName,\n type: operationType,\n duration: `${duration}ms`,\n ...(logOpts?.['includeResult'] ? { result } : {}),\n });\n}\n\n/**\n * @Instrument decorator - combines tracing, metrics, and logging\n *\n * @example\n * ```typescript\n * class UserService {\n * @Instrument({\n * operationName: 'getUser',\n * operationType: 'query',\n * trace: true,\n * metrics: true,\n * log: { level: 'debug' }\n * })\n * async getUser(id: string): Promise<User> {\n * // ...\n * }\n * }\n * ```\n */\nexport function Instrument(options: InstrumentOptions = {}): MethodDecorator {\n return function <T>(\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>\n ): TypedPropertyDescriptor<T> {\n const originalMethod = descriptor.value;\n\n if (typeof originalMethod !== 'function') {\n return descriptor;\n }\n\n const className = target.constructor.name;\n const methodName = String(propertyKey);\n const operationName = options.operationName || `${className}.${methodName}`;\n const operationType = options.operationType || 'internal';\n\n // Parse options\n let traceOpts: Record<string, unknown> | null;\n if (options.trace === true) {\n traceOpts = {};\n } else if (options.trace === false || options.trace === undefined) {\n traceOpts = null;\n } else {\n traceOpts = options.trace as Record<string, unknown>;\n }\n\n let metricOpts: Record<string, unknown> | null;\n if (options.metrics === true) {\n metricOpts = {};\n } else if (options.metrics === false || options.metrics === undefined) {\n metricOpts = null;\n } else {\n metricOpts = options.metrics as Record<string, unknown>;\n }\n\n let logOpts: Record<string, unknown> | null;\n if (options.log === true) {\n logOpts = {};\n } else if (options.log === false || options.log === undefined) {\n logOpts = null;\n } else {\n logOpts = options.log as Record<string, unknown>;\n }\n\n // Create metrics if enabled\n let durationHistogram: ReturnType<typeof createHistogram> | null = null;\n let totalCounter: ReturnType<typeof createCounter> | null = null;\n let errorCounter: ReturnType<typeof createCounter> | null = null;\n\n if (metricOpts !== null) {\n const baseName =\n (metricOpts?.['name'] as string | undefined) || `${className.toLowerCase()}_${methodName.toLowerCase()}`;\n durationHistogram = createHistogram(`${baseName}_duration_ms`, `Duration of ${operationName} in ms`);\n totalCounter = createCounter(`${baseName}_total`, `Total calls to ${operationName}`);\n errorCounter = createCounter(`${baseName}_errors_total`, `Total errors in ${operationName}`);\n }\n\n descriptor.value = async function (this: unknown, ...args: unknown[]) {\n // Check skip condition\n if (shouldSkipInstrumentation(options.skip, args)) {\n return (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n }\n\n const startTime = Date.now();\n let hasError = false;\n let result: unknown;\n\n // Start span and log entry\n const span = startInstrumentationSpan(traceOpts, operationName, operationType, methodName, className, args);\n logInstrumentationEntry(logOpts, operationName, operationType, args);\n\n try {\n result = await (originalMethod as (...args: unknown[]) => unknown).apply(this, args);\n handleInstrumentationSuccess(span, traceOpts, result);\n return result;\n } catch (error) {\n hasError = true;\n handleInstrumentationError(span, logOpts, operationName, operationType, error, startTime);\n throw error;\n } finally {\n const duration = Date.now() - startTime;\n\n if (span) {\n span.end();\n }\n\n recordInstrumentationMetrics(\n metricOpts,\n durationHistogram,\n totalCounter,\n errorCounter,\n duration,\n args,\n result,\n hasError\n );\n\n logInstrumentationExit(logOpts, operationName, operationType, duration, result, hasError);\n }\n } as T;\n\n return descriptor;\n };\n}\n\n/**\n * Helper function to create a traced function without decorators\n */\nexport function traced<T extends (...args: unknown[]) => Promise<unknown>>(\n name: string,\n fn: T,\n options?: TraceOptions\n): T {\n return (async (...args: unknown[]) => {\n if (!isFeatureEnabled('tracing')) {\n return fn(...args);\n }\n\n const tracer = getTracer();\n const span = tracer.startSpan(name, options?.kind || SpanKind.INTERNAL);\n\n if (options?.attributes) {\n span.setAttributes(options.attributes);\n }\n\n try {\n const result = await fn(...args);\n span.setStatus(SpanStatus.OK);\n return result;\n } catch (error) {\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n }) as T;\n}\n\n/**\n * Helper function to create an instrumented function without decorators\n */\nexport function instrumented<T extends (...args: unknown[]) => Promise<unknown>>(\n name: string,\n fn: T,\n options?: InstrumentOptions\n): T {\n const operationType = options?.operationType || 'internal';\n\n // Create metrics\n const durationHistogram =\n options?.metrics !== false\n ? createHistogram(`${name.toLowerCase()}_duration_ms`, `Duration of ${name} in ms`)\n : null;\n const totalCounter =\n options?.metrics !== false ? createCounter(`${name.toLowerCase()}_total`, `Total calls to ${name}`) : null;\n\n return (async (...args: unknown[]) => {\n const startTime = Date.now();\n let span: Span | null = null;\n let hasError = false;\n\n // Start span\n if (options?.trace !== false && isFeatureEnabled('tracing')) {\n span = getTracer().startSpan(name, SpanKind.INTERNAL);\n span.setAttribute('operation.type', operationType);\n }\n\n // Log entry\n if (options?.log !== false && isFeatureEnabled('logging')) {\n logger.debug(`[Enter] ${name}`, { operation: name, type: operationType });\n }\n\n try {\n const result = await fn(...args);\n if (span) span.setStatus(SpanStatus.OK);\n return result;\n } catch (error) {\n hasError = true;\n if (span && error instanceof Error) span.recordException(error);\n throw error;\n } finally {\n const duration = Date.now() - startTime;\n if (span) span.end();\n\n // Record metrics\n if (durationHistogram && isFeatureEnabled('metrics')) {\n durationHistogram.record(duration, { status: hasError ? 'error' : 'success' });\n }\n if (totalCounter && isFeatureEnabled('metrics')) {\n totalCounter.inc({ status: hasError ? 'error' : 'success' });\n }\n\n // Log exit/error\n if (options?.log !== false && isFeatureEnabled('logging')) {\n if (hasError) {\n logger.error(`[Error] ${name}`, { operation: name, duration: `${duration}ms` });\n } else {\n logger.debug(`[Exit] ${name}`, { operation: name, duration: `${duration}ms` });\n }\n }\n }\n }) as T;\n}\n","/**\n * Instrumentation Module\n *\n * Comprehensive OpenTelemetry instrumentation utilities for\n * Burdenoff microservices including tracing, metrics, and logging.\n *\n * @module instrumentation\n * @category Observability\n *\n * @example\n * ```typescript\n * import {\n * initializeInstrumentation,\n * getTracer,\n * createCounter,\n * createGraphQLInstrumentationPlugin,\n * Trace,\n * Instrument,\n * } from '@burdenoff/be-sdk/instrumentation';\n *\n * // Initialize instrumentation\n * const { tracer, metrics } = initializeInstrumentation('my-service');\n *\n * // Create a span\n * await tracer.withSpan('operation', async (span) => {\n * span.setAttribute('key', 'value');\n * // ... operation logic\n * });\n *\n * // Use decorators\n * class MyService {\n * @Trace()\n * async myMethod() { ... }\n *\n * @Instrument({ tracing: true, metrics: true, logging: true })\n * async trackedMethod() { ... }\n * }\n * ```\n */\n\n// Internal imports for initialization functions\nimport {\n getInstrumentationConfig as getConfig,\n initializeInstrumentationConfig as initConfig,\n isInstrumentationConfigInitialized as isConfigInit,\n resetInstrumentationConfig as resetConfig,\n} from './config.js';\nimport {\n getMetricsRegistry as getMetricsFn,\n initializeMetricsRegistry as initMetrics,\n isMetricsRegistryInitialized as isMetricsInit,\n resetMetricsRegistry as resetMetrics,\n} from './metrics-collector.js';\nimport {\n getTracer as getTracerFn,\n initializeTracer as initTracer,\n isTracerInitialized as isTracerInit,\n} from './tracer.js';\nimport { logger as defaultLogger, type Logger } from '../logger/index.js';\nimport { getActiveTelemetryLogger } from '../telemetry/logger-state.js';\n\n// ============================================================================\n// Simplified Setup API\n// ============================================================================\n\nimport {\n createApolloInlineTracePlugin,\n createPrometheusPlugin,\n type PrometheusPluginOptions,\n} from './graphql-plugin.js';\n\n// Configuration exports\nexport {\n buildDatabaseConfig,\n buildFeatureFlags,\n buildGraphQLConfig,\n buildInstrumentationConfig,\n buildMetricsConfig,\n buildTracingConfig,\n DEFAULT_CACHE_CONFIG,\n DEFAULT_DATABASE_CONFIG,\n DEFAULT_EVENT_QUEUE_CONFIG,\n DEFAULT_FEATURE_FLAGS,\n DEFAULT_GRAPHQL_CONFIG,\n DEFAULT_HTTP_CONFIG,\n DEFAULT_LOGGING_CONFIG,\n DEFAULT_METRICS_CONFIG,\n DEFAULT_TRACING_CONFIG,\n ENV_VARS,\n getInstrumentationConfig,\n initializeInstrumentationConfig,\n isFeatureEnabled,\n isInstrumentationConfigInitialized,\n resetInstrumentationConfig,\n updateInstrumentationConfig,\n} from './config.js';\n\n// Tracer exports\nexport {\n extractTraceContext,\n getTraceContext,\n getTracer,\n initializeTracer,\n injectTraceContext,\n isTracerInitialized,\n type Span,\n type SpanEvent,\n SpanKind,\n SpanStatus,\n startSpan,\n Tracer,\n withSpan,\n} from './tracer.js';\n\n// Metrics exports\nexport {\n type Counter,\n createCounter,\n createGauge,\n createHistogram,\n createUpDownCounter,\n DEFAULT_MAX_SERIES_PER_METRIC,\n DEFAULT_MAX_TOTAL_SERIES,\n type Gauge,\n getMetricsRegistry,\n type Histogram,\n initializeMetricsRegistry,\n isMetricsRegistryInitialized,\n type MetricLabels,\n MetricsRegistry,\n type MetricsRegistryOptions,\n OVERFLOW_LABEL_KEY,\n resetMetricsRegistry,\n type UpDownCounter,\n} from './metrics-collector.js';\n\n// Decorator exports\nexport { Instrument, instrumented, Log, Metric, Trace, traced } from './decorators.js';\n\n// GraphQL plugin exports\nexport {\n type ApolloInlineTraceOptions,\n createApolloInlineTracePlugin,\n createGraphQLInstrumentationPlugin,\n createPrometheusPlugin,\n extractOperationInfo,\n getGraphQLOperationFromContext,\n getGraphQLSpanFromContext,\n type GraphQLOperationInfo,\n type GraphQLOperationType,\n instrumentResolver,\n instrumentResolverMap,\n type InstrumentationContextExtension,\n isApolloInlineTraceAvailable,\n isPrometheusAvailable,\n normalizeOperationNameForMetric,\n type OperationNameLabelOptions,\n type PrometheusPluginOptions,\n} from './graphql-plugin.js';\n\n// Type exports\nexport type {\n CacheInstrumentationConfig,\n DatabaseInstrumentationConfig,\n EventQueueInstrumentationConfig,\n GraphQLInstrumentationConfig,\n HTTPInstrumentationConfig,\n InstrumentationConfig,\n InstrumentationFeatureFlags,\n LoggingConfig,\n MetricDefinition,\n MetricsConfig,\n OperationContext,\n SpanAttributes,\n SpanContext,\n TraceContext,\n TracingConfig,\n} from './types.js';\n\nexport { STANDARD_METRICS } from './types.js';\n\n// Re-export logger for convenience\nexport { logger } from '../logger/index.js';\n\nexport function getLogger(): Logger {\n return getActiveTelemetryLogger() ?? defaultLogger;\n}\n\n/**\n * Options for initializing instrumentation\n */\nexport interface InitializeInstrumentationOptions {\n features?: Partial<import('./types.js').InstrumentationFeatureFlags>;\n tracing?: Partial<import('./types.js').TracingConfig>;\n metrics?: Partial<import('./types.js').MetricsConfig>;\n logging?: Partial<import('./types.js').LoggingConfig>;\n graphql?: Partial<import('./types.js').GraphQLInstrumentationConfig>;\n database?: Partial<import('./types.js').DatabaseInstrumentationConfig>;\n http?: Partial<import('./types.js').HTTPInstrumentationConfig>;\n cache?: Partial<import('./types.js').CacheInstrumentationConfig>;\n eventQueue?: Partial<import('./types.js').EventQueueInstrumentationConfig>;\n}\n\n/**\n * Initialize all instrumentation components\n *\n * This is a convenience function that initializes the tracer, metrics registry,\n * and instrumentation configuration in one call.\n *\n * @param serviceName - Name of the service for tracing and metrics\n * @param options - Optional configuration overrides\n * @returns Initialized instrumentation components\n *\n * @example\n * ```typescript\n * const { tracer, metrics, config } = initializeInstrumentation('my-service', {\n * features: { tracing: true, metrics: true, logging: true },\n * tracing: { samplingRate: 0.5 },\n * });\n * ```\n */\nexport function initializeInstrumentation(\n serviceName: string,\n options?: InitializeInstrumentationOptions\n): {\n tracer: import('./tracer.js').Tracer;\n metrics: import('./metrics-collector.js').MetricsRegistry;\n config: import('./types.js').InstrumentationConfig;\n} {\n // Initialize configuration - cast options to the expected type\n // The buildInstrumentationConfig function handles merging with defaults\n initConfig(serviceName, options as unknown as Partial<import('./types.js').InstrumentationConfig>);\n\n // Initialize tracer\n initTracer(serviceName);\n\n // Initialize metrics registry with configured cardinality bounds\n initMetrics(serviceName, options?.metrics?.metricPrefix ?? '', {\n maxSeriesPerMetric: options?.metrics?.maxSeriesPerMetric,\n maxTotalSeries: options?.metrics?.maxTotalSeries,\n });\n\n return {\n tracer: getTracerFn(),\n metrics: getMetricsFn(),\n config: getConfig(),\n };\n}\n\n/**\n * Check if instrumentation is fully initialized\n */\nexport function isInstrumentationInitialized(): boolean {\n return isConfigInit() && isTracerInit() && isMetricsInit();\n}\n\n/**\n * Reset all instrumentation state (useful for testing)\n */\nexport function resetInstrumentation(): void {\n resetConfig();\n resetMetrics();\n}\n\n/**\n * Options for simplified instrumentation setup\n */\nexport interface SetupInstrumentationOptions extends InitializeInstrumentationOptions {\n /**\n * Use Apollo Federation inline tracing for automatic resolver/field-level tracing.\n * This is the recommended approach for microservices in a federated architecture.\n * @default true\n */\n useApolloInlineTrace?: boolean;\n\n /**\n * Use Prometheus metrics plugin for automatic GraphQL operation metrics.\n * This provides comprehensive metrics including:\n * - HTTP request duration\n * - GraphQL operation duration\n * - Error counts\n * - Execution phase metrics\n * - Optional resolver-level metrics\n * @default true\n */\n usePrometheus?: boolean;\n\n /**\n * Prometheus plugin configuration options.\n * Only used if usePrometheus is true.\n */\n prometheus?: PrometheusPluginOptions;\n}\n\n/**\n * Result of instrumentation setup\n */\nexport interface InstrumentationSetupResult {\n /** Initialized tracer instance */\n tracer: import('./tracer.js').Tracer;\n /** Initialized metrics registry */\n metrics: import('./metrics-collector.js').MetricsRegistry;\n /** Full instrumentation configuration */\n config: import('./types.js').InstrumentationConfig;\n /**\n * GraphQL Yoga plugins to add to your server.\n * These provide automatic tracing and metrics without manual instrumentation.\n */\n plugins: unknown[];\n}\n\n/**\n * Set up complete instrumentation for a microservice with minimal configuration.\n *\n * This is the recommended way to set up instrumentation in Burdenoff microservices.\n * It automatically configures:\n * - OpenTelemetry tracing with Apollo Federation inline traces\n * - Metrics collection\n * - GraphQL operation logging\n *\n * All you need to do is pass the returned plugins to your GraphQL Yoga server.\n *\n * @param serviceName - Name of your service (e.g., 'module-tags')\n * @param options - Optional overrides for defaults\n * @returns Instrumentation components and GraphQL plugins\n *\n * @example\n * ```typescript\n * import { setupInstrumentation } from '@burdenoff/be-sdk/instrumentation';\n * import { createYoga } from 'graphql-yoga';\n *\n * // Simple setup with all defaults\n * const { plugins, tracer, metrics } = setupInstrumentation('module-tags');\n *\n * // Create Yoga server with automatic tracing\n * const yoga = createYoga({\n * schema,\n * plugins: [...plugins, ...otherPlugins],\n * });\n *\n * // With custom overrides\n * const { plugins } = setupInstrumentation('module-tags', {\n * tracing: { samplingRate: 0.5 },\n * metrics: { metricPrefix: 'tags' },\n * });\n * ```\n */\nexport function setupInstrumentation(\n serviceName: string,\n options?: SetupInstrumentationOptions\n): InstrumentationSetupResult {\n // Initialize core instrumentation\n const { tracer, metrics, config } = initializeInstrumentation(serviceName, options);\n\n // Build plugin list\n const plugins: unknown[] = [];\n\n // Add Apollo inline trace plugin for automatic resolver/field-level tracing\n // This provides distributed tracing across federated services\n const useApollo = options?.useApolloInlineTrace ?? true;\n if (useApollo) {\n const apolloPlugin = createApolloInlineTracePlugin();\n if (apolloPlugin) {\n plugins.push(apolloPlugin);\n }\n }\n\n // Add Prometheus metrics plugin for automatic GraphQL metrics\n // This provides comprehensive metrics without manual instrumentation\n const usePrometheus = options?.usePrometheus ?? true;\n if (usePrometheus) {\n const prometheusPlugin = createPrometheusPlugin(options?.prometheus);\n if (prometheusPlugin) {\n plugins.push(prometheusPlugin);\n }\n }\n\n return {\n tracer,\n metrics,\n config,\n plugins,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkBA,IAAY,aAAL;CACL;CACA;CACA;;AACF;;;;AAKA,IAAY,WAAL;CACL;CACA;CACA;CACA;CACA;;AACF;;;;AAyDA,SAAS,kBAA0B;CACjC,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,OAAO,gBAAgB,KAAK;CAC5B,OAAO,MAAM,KAAK,KAAK,CAAC,CACrB,KAAK,M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ACF,QAAQ,KAAK,YAAY;CAE7B;CAKA,IADsB,SAAS,iBAAiB,MAC7B;EACjB,MAAM,mBAAmB,uBAAuB,SAAS,UAAU;EACnE,IAAI,kBACF,QAAQ,KAAK,gBAAgB;CAEjC;CAEA,OAAO;EACL;EACA;EACA;EACA;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"workspace-extension-COrC0dYi.js","names":[],"sources":["../src/prisma/transaction-context.ts","../src/prisma/workspace-extension.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { WorkspaceContext } from './workspace-extension.js';\n\ninterface TransactionScope {\n active: boolean;\n}\nconst contextFields = [\n 'workspaceId',\n 'tenantId',\n 'actorId',\n 'actorType',\n 'organizationId',\n 'projectId',\n 'appId',\n 'onBehalfOf',\n] as const;\n\nfunction sameContext(a: WorkspaceContext, b: WorkspaceContext): boolean {\n return contextFields.every((field) => a[field] === b[field]);\n}\n\n/**\n * Bun can assimilate a returned lazy thenable outside its async callback's ALS\n * scope. Bind only consumption of native PrismaPromises, never their creation:\n * the query stays cold and retains Prisma's brand/spec/continuation machinery.\n * This facade belongs to exactly one interactive callback, not the root client.\n */\nexport function bindTransactionContext<T extends object>(\n client: T,\n scope: TransactionScope,\n getWorkspaceContext: () => WorkspaceContext | undefined\n): T {\n const delegates = new WeakMap<object, object>();\n function bindOperation(value: unknown): unknown {\n if (!value || typeof value !== 'object' || Reflect.get(value, Symbol.toStringTag) !== 'PrismaPromise') return value;\n const sourceContext = getWorkspaceContext();\n const captured = sourceContext ? { ...sourceContext } : undefined;\n const restore = AsyncLocalStorage.snapshot();\n return new Proxy(value, {\n get(target, property, receiver) {\n const original = Reflect.get(target, property, receiver);\n if (typeof original !== 'function' || property === 'constructor') return original;\n return (...args: unknown[]) => {\n if (!scope.active)\n throw new Error('[WorkspaceExtension] Lazy operation belongs to a completed interactive transaction.');\n // snapshot() keeps ALS store references. Retain identity values too,\n // so mutating the original request object cannot retarget cold work.\n if (sourceContext && captured && !sameContext(sourceContext, captured)) {\n throw new Error('[WorkspaceExtension] Captured workspace/actor context changed before lazy execution.');\n }\n const current = getWorkspaceContext();\n if (captured && current && !sameContext(captured, current)) {\n throw new Error('[WorkspaceExtension] Lazy operation cannot cross workspace/actor context.');\n }\n // Interactive operations already belong to their native transaction.\n // Root batch promises are untouched; moving an itx promise into a new\n // batch must not replace that transaction or restore an old identity.\n if (property === 'requestTransaction')\n throw new Error('[WorkspaceExtension] Interactive operation cannot be rebound to another transaction.');\n return restore(() => {\n const result: unknown = Reflect.apply(original, target, args);\n // Fluent relation accessors return another cold PrismaPromise.\n // Capture that continuation too, without starting either query.\n return ['then', 'catch', 'finally'].includes(String(property)) ? result : bindOperation(result);\n });\n };\n },\n });\n }\n function facade(target: object, model: boolean): object {\n const existing = delegates.get(target);\n if (existing) return existing;\n const proxy = new Proxy(target, {\n get(object, property, receiver) {\n const value: unknown = Reflect.get(object, property, receiver);\n if (\n typeof value === 'function' &&\n (model || (typeof property === 'string' && !property.startsWith('_') && property !== 'constructor'))\n ) {\n return (...args: unknown[]) => bindOperation(Reflect.apply(value, object, args));\n }\n // Public custom client/model methods keep their native receiver; only\n // returned PrismaPromises are bound. Prisma model delegates are objects. Internal\n // metadata, symbols, fields, and the non-thenable client stay untouched.\n if (\n !model &&\n typeof property === 'string' &&\n !property.startsWith('_') &&\n !property.startsWith('$') &&\n value &&\n typeof value === 'object' &&\n typeof Reflect.get(value, 'findMany') === 'function'\n ) {\n return facade(value, true);\n }\n return value;\n },\n });\n delegates.set(target, proxy);\n return proxy;\n }\n return facade(client, false) as T;\n}\n","/**\n * Prisma Workspace Extension\n *\n * Automatically injects workspaceId into ALL Prisma operations using\n * request-scoped context from AsyncLocalStorage:\n *\n * **Write operations** (create, createMany, update, upsert):\n * - Auto-populates `workspaceId`, `tenantId`, `createdBy`, `updatedBy`, `context` JSON\n *\n * **Read operations** (findMany, findFirst, findUnique, count, aggregate, groupBy):\n * - Auto-injects `workspaceId` into the `where` clause for workspace isolation\n *\n * **Delete operations** (delete, deleteMany):\n * - Auto-injects `workspaceId` into the `where` clause to prevent cross-workspace deletion\n *\n * **Update where clause** (update, updateMany):\n * - Auto-injects `workspaceId` into the `where` clause to prevent cross-workspace updates\n *\n * **How it works:**\n * 1. The GraphQL server's buildContext extracts workspaceId from x-workspace-id header\n * 2. The workspace context store (AsyncLocalStorage) holds the current request's workspace info\n * 3. This Prisma extension intercepts ALL operations and auto-injects workspaceId\n *\n * **What gets auto-populated on writes:**\n * - `workspaceId` field (String or String?) - set from context if not explicitly provided\n * - `context` field (Json) - merged with workspace/actor info if not explicitly provided\n * - `tenantId` field (String or String?) - set from context if not explicitly provided\n * - `createdBy` / `updatedBy` fields - set from actor context if not explicitly provided\n *\n * **What gets auto-injected on reads/updates/deletes:**\n * - `workspaceId` in the `where` clause - ensures queries only access data within the workspace\n *\n * **Opt-out:**\n * - Explicitly providing `workspaceId` in the where/data will override auto-injection\n * - Pass `_skipWorkspaceInjection: true` in the query args to skip entirely\n * - Set `enableReadIsolation: false` in config to disable read-side injection only\n * - Add model names to `excludeModels` to skip specific models\n *\n * @module prisma/workspace-extension\n * @category Database\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { logger } from '../logger/index.js';\nimport type { InputJsonValue } from './context.js';\nimport { bindTransactionContext } from './transaction-context.js';\nimport type { AssistantSessionAttribution } from '../activity/assistant-session.js';\n\n// ============================================================================\n// Workspace Context Store (AsyncLocalStorage)\n// ============================================================================\n\n/**\n * Workspace context for the current request scope\n */\nexport interface WorkspaceContext {\n /** Workspace ID (from x-workspace-id header) */\n workspaceId?: string;\n /** Tenant ID (from x-tenant-id header or derived from workspace) */\n tenantId?: string;\n /** Actor ID (user/service/app performing the operation) */\n actorId?: string;\n /** Actor type (user, app, service, super_admin) */\n actorType?: string;\n /** Organization ID */\n organizationId?: string;\n /** Project ID */\n projectId?: string;\n /** App ID */\n appId?: string;\n /** On behalf of actor ID (for consent-based delegation) */\n onBehalfOf?: string;\n /**\n * The AI assistant session the operation runs under, when the gateway verified one\n * (BOFF-9649). `trackOperation` stamps it on every activity row written in the operation.\n */\n assistantSession?: AssistantSessionAttribution;\n}\n\n/**\n * AsyncLocalStorage for workspace context\n * This is separate from the SDK's general ContextManager to allow\n * fine-grained control over workspace-specific context propagation.\n */\nconst workspaceContextStore = new AsyncLocalStorage<WorkspaceContext>();\n\n/**\n * Fallback context for environments where AsyncLocalStorage.enterWith()\n * doesn't propagate across async boundaries (e.g., Bun + GraphQL Yoga).\n *\n * IMPORTANT: This is NOT request-isolated — it's a module-level singleton.\n * It works for single-request-at-a-time scenarios but could race under\n * concurrent requests. The ALS is the primary mechanism; this is a fallback.\n */\nlet fallbackContext: WorkspaceContext | undefined;\n\n/**\n * Set workspace context for the current async scope.\n * Call this in your GraphQL context builder or middleware.\n *\n * Uses AsyncLocalStorage.enterWith() as the primary mechanism,\n * with a module-level fallback for runtimes where enterWith()\n * doesn't propagate through all async chains (e.g., Bun).\n *\n * @param context - The workspace context for this request\n *\n * @example\n * ```typescript\n * // In your server's buildContext:\n * import { setWorkspaceContext } from '@burdenoff/be-sdk/prisma';\n *\n * buildContext: async (defaultContext) => {\n * setWorkspaceContext({\n * workspaceId: defaultContext.workspace?.id,\n * tenantId: defaultContext.tenant?.id,\n * actorId: defaultContext.actor?.id,\n * actorType: defaultContext.actor?.type,\n * organizationId: defaultContext.organization?.id,\n * });\n * return defaultContext;\n * }\n * ```\n */\nexport function setWorkspaceContext(context: WorkspaceContext): void {\n workspaceContextStore.enterWith(context);\n fallbackContext = context;\n}\n\n/**\n * Get the current workspace context from AsyncLocalStorage.\n * Falls back to module-level context if ALS returns undefined\n * (can happen in Bun where enterWith() doesn't propagate through\n * some async chains like GraphQL Yoga's execution pipeline).\n *\n * @returns The current workspace context, or undefined if not set\n */\nexport function getWorkspaceContext(): WorkspaceContext | undefined {\n return workspaceContextStore.getStore() ?? fallbackContext;\n}\n\n/**\n * The workspace context bound to the CURRENT async scope only, without the module-level fallback.\n *\n * Use it for values that must never leak between requests (for example the assistant-session\n * attribution on activity rows): the fallback holds whichever request built its context last, so a\n * background job or a concurrent request could otherwise read another request's values.\n */\nexport function getScopedWorkspaceContext(): WorkspaceContext | undefined {\n return workspaceContextStore.getStore();\n}\n\n/**\n * Run a function with a specific workspace context.\n * The context is isolated to this execution and its children.\n *\n * @param context - The workspace context\n * @param fn - The function to run\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * const result = await withWorkspaceContext(\n * { workspaceId: 'ws-123', actorId: 'user-456' },\n * async () => {\n * // All Prisma operations in here will auto-inject workspaceId\n * return await prisma.tag.create({ data: { name: 'test' } });\n * }\n * );\n * ```\n */\nexport async function withWorkspaceContext<T>(context: WorkspaceContext, fn: () => Promise<T>): Promise<T> {\n return workspaceContextStore.run(context, fn);\n}\n\n/**\n * Run a synchronous function with a specific workspace context.\n */\nexport function withWorkspaceContextSync<T>(context: WorkspaceContext, fn: () => T): T {\n return workspaceContextStore.run(context, fn);\n}\n\n// ============================================================================\n// Extension Configuration\n// ============================================================================\n\n/**\n * Configuration for the workspace extension\n */\nexport interface WorkspaceExtensionConfig {\n /**\n * Enable automatic workspaceId injection on create/update\n * @default true\n */\n enabled?: boolean;\n\n /**\n * Enable automatic workspaceId injection on read operations\n * (findMany, findFirst, findUnique, findFirstOrThrow, findUniqueOrThrow,\n * count, aggregate, groupBy)\n *\n * When enabled, every read query automatically includes `workspaceId`\n * in the `where` clause, preventing cross-workspace data leakage.\n *\n * @default true\n */\n enableReadIsolation?: boolean;\n\n /**\n * Enable automatic workspaceId injection on delete operations\n * (delete, deleteMany)\n *\n * When enabled, every delete operation automatically includes `workspaceId`\n * in the `where` clause, preventing cross-workspace deletion.\n *\n * @default true\n */\n enableDeleteIsolation?: boolean;\n\n /**\n * Enable automatic workspaceId injection into update/updateMany `where` clauses.\n *\n * When enabled, update operations automatically include `workspaceId`\n * in the `where` clause in addition to the `data` injection,\n * preventing cross-workspace updates.\n *\n * @default true\n */\n enableUpdateWhereIsolation?: boolean;\n\n /**\n * Automatically populate the `context` JSON field with workspace/actor info\n * @default true\n */\n populateContextJson?: boolean;\n\n /**\n * Automatically populate `createdBy` field on create operations\n * @default true\n */\n populateCreatedBy?: boolean;\n\n /**\n * Automatically populate `updatedBy` field on update operations\n * @default true\n */\n populateUpdatedBy?: boolean;\n\n /**\n * Automatically populate `tenantId` field from context\n * @default false (tenantId is typically derived from workspaceId at the DB level)\n */\n populateTenantId?: boolean;\n\n /**\n * Automatically populate the `onBehalfOf` field on create operations\n * (consent-based delegation tracking — defaults to the acting actor when no\n * delegation is present).\n *\n * Unlike `populateContextJson`/`populateCreatedBy`/`populateUpdatedBy`, this\n * has no per-model opt-out other than `excludeModels` (which also disables\n * RLS GUC tagging and isolation for that model). Set to `false` for services\n * whose Prisma models don't carry an `onBehalfOf` column — otherwise every\n * create on those models throws `Unknown argument onBehalfOf` from Prisma's\n * client-side validation.\n *\n * @default true\n */\n populateOnBehalfOf?: boolean;\n\n /**\n * Models to exclude from auto-injection (both reads and writes).\n * Use this for models that intentionally don't have workspaceId.\n *\n * Common exclusions: system tables, infra tables, global reference data.\n *\n * @default []\n */\n excludeModels?: string[];\n\n /**\n * Models to exclude from read isolation only.\n * These models will still get write-side injection (workspaceId on create)\n * but reads will NOT have workspaceId auto-injected into `where`.\n *\n * Use this for child/join tables where workspace scoping is inherited\n * through parent relations, or for models queried by ID that don't\n * have a workspaceId column.\n *\n * @default []\n */\n excludeModelsFromReadIsolation?: string[];\n\n /**\n * When true, throws an error if workspaceId is missing from context\n * for any non-excluded model operation. This prevents silent\n * workspace-unscoped queries that could leak data across workspaces.\n *\n * When false, operations without workspace context proceed without\n * workspaceId injection (legacy behavior).\n *\n * @default true\n */\n strictMode?: boolean;\n\n /**\n * Operations that are allowed without workspace context even in strict mode.\n * Use `Model.operation` format (e.g., `['Workspace.create', 'RevokedToken.findMany']`).\n *\n * Valid operation names: create, createMany, createManyAndReturn, update, updateMany,\n * upsert, findMany, findFirst, findFirstOrThrow, findUnique, findUniqueOrThrow,\n * count, aggregate, groupBy, delete, deleteMany.\n *\n * @default []\n */\n allowedUnguardedOperations?: string[];\n\n /**\n * Log injection events (useful for debugging)\n * @default false\n */\n debug?: boolean;\n\n /**\n * Tag the PostgreSQL connection with workspace attribution for pg_stat_activity visibility.\n *\n * When enabled, the first DB operation per workspace context sets:\n * `application_name = 'svc=<SERVICE_NAME>;ws=<workspaceId>'`\n *\n * This makes workspace-level query attribution visible in pg_stat_activity,\n * pg_locks, auto_explain, and monitoring tools without any schema changes.\n * Subsequent operations in the same request are deduplicated via WeakSet,\n * costing ~0 overhead after the first round-trip per request context.\n *\n * NOTE: This is a session-level SET so attribution may drift across ops\n * that reuse the same pooled connection from different requests. Use for\n * aggregate observability, not per-query forensics.\n *\n * @default false\n */\n enableApplicationNameTagging?: boolean;\n\n /**\n * Set the `app.workspace_id` GUC for Row Level Security enforcement.\n *\n * When enabled, every workspace-scoped operation runs with\n * `SET LOCAL app.workspace_id = '<workspaceId>'`\n * in effect (see \"Transactions\" below for how that is scoped).\n *\n * RLS policies using `current_setting('app.workspace_id', true)` then filter\n * rows by workspace, providing a defense-in-depth backstop to the application-\n * layer workspaceId injection in the WHERE clause.\n *\n * Pair with migrations that run per table:\n * `ALTER TABLE t ENABLE ROW LEVEL SECURITY;`\n * `CREATE POLICY ws_isolation ON t\n * USING (workspace_id = current_setting('app.workspace_id', true))\n * WITH CHECK (workspace_id = current_setting('app.workspace_id', true));`\n *\n * Fail-closed semantics: if the GUC is unset (NULL from missing_ok=true),\n * `workspace_id = NULL` is always false, so RLS returns no rows — leaking\n * nothing rather than everything.\n *\n * Transactions: a standalone operation runs in its own short transaction\n * (`SET LOCAL` + the operation). An operation on the `tx` client inside a\n * caller's `$transaction(async (tx) => …)`, including raw SQL, runs in the\n * caller's transaction, after one `set_config(..., true)` per transaction and\n * workspace, so it is atomic with the rest of that transaction and its row\n * locks are held until commit. `$transaction([...])` batches get the same\n * statement prepended (BOFF-8874).\n *\n * @default false\n */\n enableRlsGucTagging?: boolean;\n}\n\n/**\n * Default configuration. Exported so consumers/tests can spread over the\n * real defaults (`{ ...defaultWorkspaceExtensionConfig, populateOnBehalfOf: false }`)\n * instead of re-declaring every field.\n */\nexport const defaultWorkspaceExtensionConfig: Required<WorkspaceExtensionConfig> = {\n enabled: true,\n enableReadIsolation: true,\n enableDeleteIsolation: true,\n enableUpdateWhereIsolation: true,\n populateContextJson: true,\n populateCreatedBy: true,\n populateUpdatedBy: true,\n populateTenantId: false,\n populateOnBehalfOf: true,\n excludeModels: [],\n excludeModelsFromReadIsolation: [],\n strictMode: true,\n allowedUnguardedOperations: [],\n debug: false,\n enableApplicationNameTagging: false,\n enableRlsGucTagging: false,\n};\n\n// ============================================================================\n// Data Injection Helpers\n// ============================================================================\n\n/**\n * Check if a field exists in the data object (including being set to null/undefined explicitly)\n */\nfunction hasField(data: Record<string, unknown>, field: string): boolean {\n return field in data;\n}\n\n/**\n * Inject workspace-related fields into create data.\n *\n * Exported (alongside `injectWhereWorkspaceId`) so consumers can unit-test\n * exactly what a given `WorkspaceExtensionConfig` injects for their own\n * Prisma schema — in particular, to verify `populateOnBehalfOf: false` /\n * `populateContextJson: false` actually suppress `onBehalfOf`/`context`\n * before wiring the extension against models that don't have those columns.\n */\nexport function injectCreateFields(\n data: Record<string, unknown>,\n wsCtx: WorkspaceContext,\n config: Required<WorkspaceExtensionConfig>\n): Record<string, unknown> {\n const injected = { ...data };\n\n // Inject workspaceId if not already provided\n if (wsCtx.workspaceId && !hasField(injected, 'workspaceId')) {\n injected['workspaceId'] = wsCtx.workspaceId;\n }\n\n // Inject tenantId if configured and not already provided\n if (config.populateTenantId && wsCtx.tenantId && !hasField(injected, 'tenantId')) {\n injected['tenantId'] = wsCtx.tenantId;\n }\n\n // Inject createdBy if configured and not already provided\n if (config.populateCreatedBy && wsCtx.actorId && !hasField(injected, 'createdBy')) {\n injected['createdBy'] = wsCtx.actorId;\n }\n\n // Inject updatedBy on create as well (initial value)\n if (config.populateUpdatedBy && wsCtx.actorId && !hasField(injected, 'updatedBy')) {\n injected['updatedBy'] = wsCtx.actorId;\n }\n\n // Inject onBehalfOf (for consent-based delegation tracking)\n // If onBehalfOf is in context (from consent), use it; otherwise defaults to actorId (self-action)\n if (config.populateOnBehalfOf && wsCtx.onBehalfOf && !hasField(injected, 'onBehalfOf')) {\n injected['onBehalfOf'] = wsCtx.onBehalfOf;\n } else if (config.populateOnBehalfOf && wsCtx.actorId && !hasField(injected, 'onBehalfOf')) {\n // Default to actorId if no delegation (self-action)\n injected['onBehalfOf'] = wsCtx.actorId;\n }\n\n // Populate context JSON field\n if (config.populateContextJson && !hasField(injected, 'context')) {\n const contextJson = buildContextJsonFromWorkspaceContext(wsCtx);\n if (contextJson) {\n injected['context'] = contextJson;\n }\n }\n\n return injected;\n}\n\n/**\n * Inject workspace-related fields into update data\n */\nfunction injectUpdateFields(\n data: Record<string, unknown>,\n wsCtx: WorkspaceContext,\n config: Required<WorkspaceExtensionConfig>\n): Record<string, unknown> {\n const injected = { ...data };\n\n // Inject updatedBy if configured and not already provided\n if (config.populateUpdatedBy && wsCtx.actorId && !hasField(injected, 'updatedBy')) {\n injected['updatedBy'] = wsCtx.actorId;\n }\n\n // Note: We intentionally do NOT auto-inject workspaceId on updates\n // because updates target existing records (workspaceId is immutable after creation)\n // and changing it would be a data integrity issue.\n\n return injected;\n}\n\n/**\n * Inject workspaceId into a where clause.\n * Only injects if workspaceId is available in context and not already present in where.\n *\n * For operations that may not have a where clause (e.g., findMany without filters),\n * creates a new where object with just workspaceId.\n */\nfunction injectWhereClause(\n where: Record<string, unknown> | undefined,\n wsCtx: WorkspaceContext\n): Record<string, unknown> | undefined {\n if (!wsCtx.workspaceId) return where;\n\n if (!where) {\n // No where clause exists, create one with just workspaceId\n return { workspaceId: wsCtx.workspaceId };\n }\n\n // Only inject if not already present\n if (!hasField(where, 'workspaceId')) {\n return { ...where, workspaceId: wsCtx.workspaceId };\n }\n\n return where;\n}\n\n/**\n * Build context JSON from workspace context\n */\nfunction buildContextJsonFromWorkspaceContext(wsCtx: WorkspaceContext): InputJsonValue | undefined {\n const context: Record<string, string> = {};\n\n if (wsCtx.workspaceId) context['workspaceId'] = wsCtx.workspaceId;\n if (wsCtx.actorId) context['userId'] = wsCtx.actorId;\n if (wsCtx.organizationId) context['organizationId'] = wsCtx.organizationId;\n if (wsCtx.projectId) context['projectId'] = wsCtx.projectId;\n if (wsCtx.appId) context['appId'] = wsCtx.appId;\n\n return Object.keys(context).length > 0 ? context : undefined;\n}\n\n/**\n * Inject workspaceId into where clause for read/update/delete operations.\n * This is a utility function exported for services that want to manually\n * add workspace scoping to their queries.\n *\n * @param where - The existing where clause\n * @param wsCtx - The workspace context (or auto-detected from AsyncLocalStorage)\n * @returns The where clause with workspaceId injected if not already present\n *\n * @example\n * ```typescript\n * import { injectWhereWorkspaceId, getWorkspaceContext } from '@burdenoff/be-sdk/prisma';\n *\n * const wsCtx = getWorkspaceContext();\n * const where = injectWhereWorkspaceId({ status: 'ACTIVE' }, wsCtx);\n * // Result: { status: 'ACTIVE', workspaceId: 'ws-123' }\n * ```\n */\nexport function injectWhereWorkspaceId(\n where: Record<string, unknown> | undefined,\n wsCtx?: WorkspaceContext\n): Record<string, unknown> | undefined {\n const ctx = wsCtx ?? getWorkspaceContext();\n if (!where || !ctx?.workspaceId) return where;\n\n // Only inject if not already present\n if (!hasField(where, 'workspaceId')) {\n return { ...where, workspaceId: ctx.workspaceId };\n }\n\n return where;\n}\n\n/**\n * Remove the _skipWorkspaceInjection flag from args before passing to Prisma.\n * Using a dedicated function avoids ESLint unused-variable warnings from destructuring.\n */\nfunction stripSkipFlag<T extends Record<string, unknown>>(args: T): Omit<T, '_skipWorkspaceInjection'> {\n const cleaned = { ...args };\n delete (cleaned as Record<string, unknown>)['_skipWorkspaceInjection'];\n return cleaned;\n}\n\n/**\n * Check if a model should be excluded from read isolation.\n * A model is excluded if it's in excludeModels OR excludeModelsFromReadIsolation.\n */\nfunction isExcludedFromReadIsolation(model: string, config: Required<WorkspaceExtensionConfig>): boolean {\n return config.excludeModels.includes(model) || config.excludeModelsFromReadIsolation.includes(model);\n}\n\n// ============================================================================\n// Strict Mode Enforcement\n// ============================================================================\n\n/**\n * Enforce strict mode: throw if workspace context is missing and the operation\n * is not explicitly allowed to run without it.\n *\n * @returns true if the operation should proceed without workspace injection (non-strict or allowed)\n * @throws Error if strict mode is enabled and the operation is not allowed\n */\nfunction enforceStrictMode(\n model: string,\n operation: string,\n wsCtx: WorkspaceContext | undefined,\n config: Required<WorkspaceExtensionConfig>\n): void {\n // If workspace context has a workspaceId, nothing to enforce\n if (wsCtx?.workspaceId) return;\n\n // If strict mode is off, allow silently\n if (!config.strictMode) return;\n\n // Check if this specific operation is allowed without workspace context\n const opKey = `${model}.${operation}`;\n if (config.allowedUnguardedOperations.includes(opKey)) return;\n\n // Strict mode violation — throw\n throw new Error(\n `[WorkspaceExtension] Workspace context required for ${model}.${operation}. ` +\n `No workspaceId found in request context. To bypass, either: ` +\n `(1) add \"${model}\" to excludeModels, ` +\n `(2) add \"${opKey}\" to allowedUnguardedOperations, or ` +\n `(3) pass _skipWorkspaceInjection: true in the query args.`\n );\n}\n\n// ============================================================================\n// Prisma Extension\n// ============================================================================\n\n/**\n * Standard args shape for operations with a `where` clause\n */\ninterface WhereArgs {\n where?: Record<string, unknown>;\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Standard handler params from Prisma $extends\n */\ninterface ExtensionHandlerParams<TArgs> {\n model: string;\n args: TArgs;\n query: (args: unknown) => Promise<unknown>;\n /** Prisma-internal request params; `transaction` identifies a caller transaction. */\n __internalParams?: PrismaQueryInternalParams;\n}\n\n/** Handler params for top-level raw operations (`$queryRaw`, `$executeRaw`, …). */\ninterface RawOperationHandlerParams {\n args: unknown;\n query: (args: unknown) => Promise<unknown>;\n __internalParams?: PrismaQueryInternalParams;\n}\n\n/** Client surface the `$transaction` wrapper delegates to (the client one layer down). */\ntype TransactionDelegate = {\n $transaction: (input: unknown, options?: unknown) => Promise<unknown>;\n};\n\n/**\n * Add workspace extension to a Prisma client.\n *\n * This extension provides comprehensive workspace isolation by automatically\n * injecting workspaceId into ALL Prisma operations:\n *\n * **Writes**: Auto-populates workspaceId, tenantId, createdBy, updatedBy, context JSON\n * **Reads**: Auto-injects workspaceId into where clause (findMany, findFirst, etc.)\n * **Updates**: Auto-injects workspaceId into where clause + updatedBy into data\n * **Deletes**: Auto-injects workspaceId into where clause\n *\n * **Chain order matters**: Apply this extension AFTER the graph extension\n * (handled automatically by createDatabaseClient).\n *\n * @param baseClient - The Prisma client to extend\n * @param config - Extension configuration\n * @returns Extended Prisma client with workspace auto-injection\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { addWorkspaceExtension } from '@burdenoff/be-sdk/prisma';\n *\n * const baseClient = new PrismaClient({ adapter });\n * const client = addWorkspaceExtension(baseClient, {\n * populateContextJson: true,\n * populateCreatedBy: true,\n * enableReadIsolation: true,\n * debug: process.env.NODE_ENV === 'development',\n * excludeModels: ['CircuitBreakerState', 'SchedulerState'],\n * excludeModelsFromReadIsolation: ['Permission', 'RbacResourceType'],\n * });\n * ```\n */\n// ============================================================================\n// Connection Tagging (Phase 0.2)\n// ============================================================================\n\n/** Minimal Prisma raw-exec surface needed for SET application_name */\ntype RawPrismaForTagging = {\n $executeRawUnsafe: (query: string, ...values: unknown[]) => Promise<number>;\n};\n\n/**\n * WeakSet of contexts that have already had the connection tagged this request.\n * WorkspaceContext objects live only for the duration of a request, so entries\n * are automatically GC'd when the context goes out of scope — no manual cleanup.\n */\nconst taggedContexts = new WeakSet<WorkspaceContext>();\n\n/**\n * Tag the current Postgres connection with workspace attribution (once per context).\n * Sets `application_name = 'svc=<name>;ws=<workspaceId>'` at the session level.\n * Non-fatal: tagging failures are swallowed so the main operation still proceeds.\n *\n * @internal Exported for unit testing only — do not call from product code.\n */\nexport async function maybeTagConnection(rawPrisma: RawPrismaForTagging, wsCtx: WorkspaceContext): Promise<void> {\n if (taggedContexts.has(wsCtx)) return;\n taggedContexts.add(wsCtx);\n // Strip non-safe chars; workspace IDs are UUIDs/CUIDs, service names are kebab-case\n const safeSvc = (process.env['SERVICE_NAME'] ?? 'svc').replace(/[^a-zA-Z0-9\\-_]/g, '');\n const safeWs = (wsCtx.workspaceId ?? '').replace(/[^a-zA-Z0-9\\-_]/g, '');\n const tag = `svc=${safeSvc};ws=${safeWs}`;\n try {\n await rawPrisma.$executeRawUnsafe(`SET application_name = '${tag}'`);\n } catch {\n // Retry on the next operation if this one failed\n taggedContexts.delete(wsCtx);\n }\n}\n\n// ============================================================================\n// RLS GUC Tagging (Phase 3)\n// ============================================================================\n\n/**\n * WeakSet of contexts that have already had the RLS GUC set this request.\n */\nconst rlsTaggedContexts = new WeakSet<WorkspaceContext>();\n\n/**\n * Set `app.workspace_id` GUC for RLS enforcement (once per context, session-level).\n *\n * When set, RLS policies using `current_setting('app.workspace_id', true)` filter\n * rows to the current workspace. Non-fatal: failures are swallowed and retried on\n * the next operation via WeakSet entry removal.\n *\n * NOT used by the extension's operation handlers below (see\n * `runOperationWithRlsGuc`) — session-level `SET` is unsafe once traffic is routed\n * through PgBouncer in transaction-pooling mode (see that function's doc comment\n * for the full incident writeup, BOFF-5488). Kept as a standalone export, still\n * unit tested, for any caller that genuinely runs on an unpooled/session-pooled\n * connection where session-level `SET` is sufficient.\n *\n * @internal Exported for unit testing only — do not call from product code.\n */\nexport async function maybeSetRlsGuc(rawPrisma: RawPrismaForTagging, wsCtx: WorkspaceContext): Promise<void> {\n if (rlsTaggedContexts.has(wsCtx)) return;\n rlsTaggedContexts.add(wsCtx);\n // Allow alphanumeric, hyphens, underscores — CUID/UUID safe, prevents SQL injection\n const safeWs = (wsCtx.workspaceId ?? '').replace(/[^a-zA-Z0-9\\-_]/g, '');\n try {\n await rawPrisma.$executeRawUnsafe(`SET app.workspace_id = '${safeWs}'`);\n } catch {\n // Retry on the next operation if this one failed\n rlsTaggedContexts.delete(wsCtx);\n }\n}\n\n/**\n * A Prisma interactive-transaction client (`tx` inside `$transaction(async (tx) =>\n * …)`), typed with just enough surface for `runOperationWithRlsGuc`: raw SQL\n * execution, plus one delegate per model keyed by its Prisma Client property name\n * (e.g. `customer`, `driver`). The index signature is `unknown` (not a concrete\n * delegate shape) because this helper is generic across every model in the schema\n * — callers narrow and verify the specific delegate/method they need at runtime.\n */\ntype PrismaTxForRlsGuc = {\n $executeRawUnsafe: (query: string, ...values: unknown[]) => Promise<number>;\n [modelClientProperty: string]: unknown;\n};\n\n/** Minimal Prisma client surface needed to open an interactive transaction. */\ntype RawPrismaForRlsTransaction = {\n $transaction: <TResult>(fn: (tx: PrismaTxForRlsGuc) => Promise<TResult>) => Promise<TResult>;\n};\n\n/**\n * Prisma DMMF model name (e.g. `Customer`) -> Prisma Client delegate property\n * (e.g. `customer`). Matches Prisma's own client-generation rule: lower-case the\n * first character, leave the rest untouched.\n */\nfunction modelToClientProperty(model: string): string {\n return model.length > 0 ? model.charAt(0).toLowerCase() + model.slice(1) : model;\n}\n\n/**\n * Run a single Prisma operation with `app.workspace_id` set as a\n * **transaction-scoped** (`SET LOCAL`) GUC immediately ahead of it, so Postgres\n * RLS policies using `current_setting('app.workspace_id', true)` see the right\n * value for both the `USING` (read) and `WITH CHECK` (write) clauses.\n *\n * Session-level `SET` (`maybeSetRlsGuc` above, the original Phase 3\n * implementation) is NOT safe once traffic goes through PgBouncer in\n * **transaction pooling mode** — the mode configured on all four\n * `boff-pg-{global,wspace}-{alpha,prod}-cin` servers' built-in PgBouncer (see\n * infra-specs/current-architecture/02-database-postgres-age.md). PgBouncer hands\n * the physical backend connection back to the pool after every standalone\n * statement/implicit transaction, so a `SET` executed by one statement is not\n * guaranteed visible to the very next one, even over what looks like the same\n * logical client connection.\n *\n * This was exactly BOFF-5488: `wspace-movethewheels-svc`'s RLS Phase 3b (FORCE\n * ROW LEVEL SECURITY + a non-owner runtime role, `wspace_movethewheels_app`,\n * pointed at the pooled `:6432` connection) made the `ws_isolation` policy bind\n * for real, but the session-level `SET` from `maybeSetRlsGuc` was landing on a\n * different pooled backend connection than the write that followed it — so every\n * write failed `WITH CHECK` (`new row violates row-level security policy`) and\n * every read matched zero rows.\n *\n * A Prisma **interactive transaction** (`$transaction(async (tx) => …)`) pins one\n * physical connection for the callback's full duration — PgBouncer sees a single\n * unbroken `BEGIN … COMMIT` and cannot reassign the backend mid-transaction — so\n * `SET LOCAL` inside it is guaranteed visible to the operation issued right after\n * it in the same callback. Safe under transaction-mode pooling, session-mode\n * pooling, and with no pooler in front of Postgres at all. The extra round trip\n * (one interactive transaction instead of one direct call) only applies to\n * services that opt into `enableRlsGucTagging` — off by default.\n *\n * @internal Legacy exported helper retained for compatibility and its historical\n * tests. It reissues a model call and cannot preserve surrounding query hooks;\n * addWorkspaceExtension uses the continuation-based route below instead. Do not\n * call this helper from product code.\n */\nexport async function runOperationWithRlsGuc<TResult>(\n rootClient: RawPrismaForRlsTransaction,\n wsCtx: WorkspaceContext,\n model: string,\n operation: string,\n args: unknown\n): Promise<TResult> {\n const safeWs = (wsCtx.workspaceId ?? '').replace(/[^a-zA-Z0-9\\-_]/g, '');\n const clientProperty = modelToClientProperty(model);\n return rootClient.$transaction(async (tx) => {\n await tx.$executeRawUnsafe(`SET LOCAL app.workspace_id = '${safeWs}'`);\n // `tx[clientProperty]` is typed `unknown` (see PrismaTxForRlsGuc) because this\n // helper is generic across every model; narrow to the minimal callable shape\n // needed and verify at runtime before invoking rather than trusting a cast.\n const delegate = tx[clientProperty] as Record<string, (opArgs: unknown) => Promise<TResult>> | undefined;\n const method = delegate?.[operation];\n if (typeof method !== 'function') {\n throw new Error(\n `[WorkspaceExtension] Unable to resolve ${model}.${operation} (client property \"${clientProperty}\") ` +\n 'on the interactive-transaction client for RLS GUC tagging.'\n );\n }\n return method(args);\n });\n}\n\n/** Minimal batch surface; both operations must stay lazy until Prisma binds them. */\ntype RawPrismaForRlsContinuation = {\n $executeRawUnsafe: (sql: string, ...values: unknown[]) => PendingRawStatement;\n $transaction: <TResult>(input: [PendingRawStatement, Promise<TResult>]) => Promise<[unknown, TResult]>;\n};\n\n/**\n * Keep the original query continuation, including later query extensions, inside\n * the GUC-tagged transaction. Reissuing a model call on the root client would\n * skip later hooks, or execute an earlier hook twice (BOFF-8874).\n */\nasync function runQueryWithRlsGuc<TResult>(\n rootClient: RawPrismaForRlsContinuation,\n wsCtx: WorkspaceContext,\n query: () => Promise<TResult>\n): Promise<TResult> {\n // Prisma types this as Promise, but its extension callback returns a lazy\n // PrismaPromise. Require the binding capability instead of falling back to an\n // independent model call or executing the query outside the transaction.\n const pendingQuery = query() as Promise<TResult> & { requestTransaction?: unknown };\n const pendingContext = rootClient.$executeRawUnsafe(\n \"SELECT set_config('app.workspace_id', $1, true), \" +\n \"set_config('statement_timeout', CASE \" +\n \"WHEN current_setting('statement_timeout')::interval > interval '0' \" +\n \"AND current_setting('statement_timeout')::interval < interval '5 seconds' \" +\n \"THEN current_setting('statement_timeout') ELSE '5000ms' END, true)\",\n sanitizeWorkspaceId(wsCtx.workspaceId)\n );\n if (\n typeof pendingQuery.requestTransaction !== 'function' ||\n typeof pendingContext.requestTransaction !== 'function'\n ) {\n throw new Error(\n '[WorkspaceExtension] RLS query continuation requires transaction-bindable PrismaPromises; ' +\n 'refusing the unsupported Prisma integration (BOFF-8874).'\n );\n }\n const [, result] = await rootClient.$transaction([pendingContext, pendingQuery]);\n return result;\n}\n\n// ============================================================================\n// Caller transactions (BOFF-8874)\n// ============================================================================\n//\n// `runOperationWithRlsGuc` above opens its OWN interactive transaction per\n// operation. That is right for a standalone call, but wrong when the operation is\n// issued on the `tx` client inside a caller's `prisma.$transaction(...)`: the\n// operation would commit on another connection, so the caller's transaction\n// would not be atomic and its `SELECT … FOR UPDATE` fences would run without the\n// GUC (matching no rows under FORCE RLS, so locking nothing).\n//\n// Inside a caller transaction the extension now runs the context statement\n// (`set_config(..., is_local => true)`, identical to `SET LOCAL`) on the caller's\n// transaction itself, once per transaction and workspace, and then executes the\n// operation in place. Batch transactions (`$transaction([...])`) get the same\n// statement prepended to the batch by the client-level `$transaction` wrapper in\n// `addWorkspaceExtension`. Outside any transaction nothing changes.\n\n/**\n * Prisma passes the transaction an operation belongs to on the query-extension\n * callback's `__internalParams.transaction`: `{ kind: 'itx', id, payload }` for an\n * interactive transaction, `{ kind: 'batch', … }` for `$transaction([...])`, and\n * nothing for a standalone call. The `live-pg` contract test pins this down\n * against the installed Prisma version.\n */\nexport interface PrismaQueryInternalParams {\n transaction?: unknown;\n}\n\n/** The caller transaction an operation runs in, if any. */\nexport type CallerTransaction = { kind: 'itx'; id: string; descriptor: object } | { kind: 'batch' };\n\n/**\n * Classify the transaction an extension callback is running in.\n *\n * Throws on a transaction descriptor this version does not understand rather\n * than guessing: running such an operation down the standalone path would\n * silently break the caller's atomicity again.\n *\n * @internal Exported for unit testing only — do not call from product code.\n */\nexport function getCallerTransaction(\n internalParams: PrismaQueryInternalParams | undefined\n): CallerTransaction | undefined {\n const transaction = internalParams?.transaction;\n if (transaction === undefined || transaction === null) return undefined;\n if (typeof transaction === 'object') {\n const { kind, id } = transaction as { kind?: unknown; id?: unknown };\n if (kind === 'itx' && typeof id === 'string' && id.length > 0) {\n return { kind: 'itx', id, descriptor: transaction };\n }\n if (kind === 'batch') return { kind: 'batch' };\n }\n throw new Error(\n '[WorkspaceExtension] Unrecognised Prisma transaction descriptor on __internalParams.transaction; ' +\n 'refusing to run the operation outside the caller transaction. This Prisma version is not supported ' +\n 'by the be-sdk RLS transaction integration (BOFF-8874).'\n );\n}\n\n/** Same sanitisation as the standalone path: CUID/UUID-safe, prevents SQL injection. */\nfunction sanitizeWorkspaceId(workspaceId: string | undefined): string {\n return (workspaceId ?? '').replace(/[^a-zA-Z0-9\\-_]/g, '');\n}\n\n/** Same tag `maybeTagConnection` sets: `svc=<SERVICE_NAME>;ws=<workspaceId>`. */\nfunction buildApplicationNameTag(wsCtx: WorkspaceContext): string {\n const safeSvc = (process.env['SERVICE_NAME'] ?? 'svc').replace(/[^a-zA-Z0-9\\-_]/g, '');\n return `svc=${safeSvc};ws=${sanitizeWorkspaceId(wsCtx.workspaceId)}`;\n}\n\n/** A single parameterised statement that sets the transaction-local context. */\nexport interface TransactionContextStatement {\n sql: string;\n params: string[];\n /** Identifies the values set, so a transaction only re-runs it when they change. */\n key: string;\n}\n\n/**\n * Build the transaction-local context statement for the enabled tagging modes,\n * or `undefined` when neither RLS GUC nor application_name tagging is on.\n * `set_config(name, value, true)` is exactly `SET LOCAL name = value`.\n *\n * @internal Exported for unit testing only — do not call from product code.\n */\nexport function buildTransactionContextStatement(\n wsCtx: WorkspaceContext,\n config: Pick<Required<WorkspaceExtensionConfig>, 'enableRlsGucTagging' | 'enableApplicationNameTagging'>\n): TransactionContextStatement | undefined {\n const settings: string[] = [];\n const params: string[] = [];\n if (config.enableRlsGucTagging) {\n params.push(sanitizeWorkspaceId(wsCtx.workspaceId));\n settings.push(`set_config('app.workspace_id', $${params.length}, true)`);\n }\n if (config.enableApplicationNameTagging) {\n params.push(buildApplicationNameTag(wsCtx));\n settings.push(`set_config('application_name', $${params.length}, true)`);\n }\n if (settings.length === 0) return undefined;\n return { sql: `SELECT ${settings.join(', ')}`, params, key: params.join('\\u0000') };\n}\n\n/**\n * A raw Prisma statement before it runs. Prisma's lazy `PrismaPromise` exposes\n * `requestTransaction(descriptor)`, which is how `$transaction` binds statements to\n * a transaction; the extension uses it to run the context statement on the\n * caller's transaction instead of a pooled connection of its own.\n */\ntype PendingRawStatement = PromiseLike<number> & {\n requestTransaction?: (transaction: object) => PromiseLike<unknown>;\n};\n\n/** Unextended client surface for issuing the context statement. */\nexport type RawPrismaForCallerTransaction = {\n $executeRawUnsafe: (query: string, ...values: unknown[]) => PendingRawStatement;\n};\n\ninterface CallerTransactionState {\n /** Descriptor of the (possibly nested) transaction level the context was set on. */\n descriptor: object;\n key: string;\n ready: Promise<void>;\n inflight: number;\n}\n\n/**\n * Context already applied per caller transaction id. Bounded: an evicted entry\n * only costs one repeated context statement, never correctness.\n */\nconst MAX_TRACKED_CALLER_TRANSACTIONS = 4096;\nconst callerTransactionStates = new Map<string, CallerTransactionState>();\n\nfunction rememberCallerTransaction(id: string, state: CallerTransactionState): void {\n callerTransactionStates.delete(id);\n callerTransactionStates.set(id, state);\n if (callerTransactionStates.size > MAX_TRACKED_CALLER_TRANSACTIONS) {\n const oldest = callerTransactionStates.keys().next().value;\n if (oldest !== undefined) callerTransactionStates.delete(oldest);\n }\n}\n\nasync function applyCallerTransactionContext(\n rawPrisma: RawPrismaForCallerTransaction,\n descriptor: object,\n statement: TransactionContextStatement\n): Promise<void> {\n const pending = rawPrisma.$executeRawUnsafe(statement.sql, ...statement.params);\n if (typeof pending.requestTransaction !== 'function') {\n throw new Error(\n '[WorkspaceExtension] Cannot bind the RLS context statement to the caller transaction ' +\n '(PrismaPromise.requestTransaction is unavailable); refusing to run it on another connection (BOFF-8874).'\n );\n }\n await pending.requestTransaction(descriptor);\n}\n\n/**\n * Run `run` (the operation, already bound to the caller's interactive\n * transaction by Prisma) after making sure that transaction carries the\n * workspace context. The context statement runs on the caller's transaction,\n * once per transaction level and workspace: a later operation for the same\n * workspace costs no extra round trip, a workspace switch re-runs it, and so does\n * the first operation after entering or leaving a nested transaction (a\n * savepoint rollback reverts `SET LOCAL`, a release keeps it).\n *\n * Concurrent operations for *different* workspaces on one transaction cannot be\n * isolated from each other, so that case throws instead of risking one running\n * under the other's GUC.\n *\n * @internal Exported for unit testing only — do not call from product code.\n */\nexport async function runOperationInCallerTransaction<TResult>(\n rawPrisma: RawPrismaForCallerTransaction,\n transaction: { id: string; descriptor: object },\n wsCtx: WorkspaceContext,\n config: Pick<Required<WorkspaceExtensionConfig>, 'enableRlsGucTagging' | 'enableApplicationNameTagging'>,\n run: () => Promise<TResult>\n): Promise<TResult> {\n const statement = buildTransactionContextStatement(wsCtx, config);\n if (!statement) return run();\n\n let state = callerTransactionStates.get(transaction.id);\n if (!state || state.descriptor !== transaction.descriptor || state.key !== statement.key) {\n if (state && state.inflight > 0 && state.key !== statement.key) {\n throw new Error(\n '[WorkspaceExtension] Concurrent operations for different workspaces inside one transaction are not ' +\n 'supported: the RLS context is per transaction. Await the other workspace’s operations first.'\n );\n }\n const next: CallerTransactionState = {\n descriptor: transaction.descriptor,\n key: statement.key,\n ready: applyCallerTransactionContext(rawPrisma, transaction.descriptor, statement),\n inflight: 0,\n };\n next.ready.catch(() => {\n if (callerTransactionStates.get(transaction.id) === next) callerTransactionStates.delete(transaction.id);\n });\n rememberCallerTransaction(transaction.id, next);\n state = next;\n }\n\n state.inflight += 1;\n try {\n await state.ready;\n return await run();\n } finally {\n state.inflight -= 1;\n }\n}\n\n/** @internal Test hook: forget all tracked caller transactions. */\nexport function resetCallerTransactionStateForTests(): void {\n callerTransactionStates.clear();\n}\n\nexport function addWorkspaceExtension<T>(baseClient: T, config?: WorkspaceExtensionConfig): T {\n const fullConfig: Required<WorkspaceExtensionConfig> = {\n ...defaultWorkspaceExtensionConfig,\n ...config,\n };\n\n if (!fullConfig.enabled) {\n logger.info('[WorkspaceExtension] Extension disabled by configuration');\n return baseClient;\n }\n\n // Capture the unwrapped client for connection tagging (pre-extension, avoids recursion)\n const rawPrisma = baseClient as unknown as RawPrismaForTagging;\n // Same unwrapped client, typed for a lazy query-continuation batch; no new pool.\n const rawPrismaForContinuations = baseClient as unknown as RawPrismaForRlsContinuation;\n // Capture the pre-wrapper transaction method, but preserve its final receiver\n // when invoked. Selecting $parent would discard query extensions added later.\n const transactionDelegate = (baseClient as unknown as TransactionDelegate).$transaction;\n // Same unwrapped client again, typed for binding the context statement to a\n // caller's transaction (see runOperationInCallerTransaction).\n const rawPrismaForCallerTransactions = baseClient as unknown as RawPrismaForCallerTransaction;\n const tagsTransactions = fullConfig.enableRlsGucTagging || fullConfig.enableApplicationNameTagging;\n\n /**\n * Execute an operation whose args have already been workspace-injected.\n *\n * - Inside a caller's interactive transaction: set the context on that\n * transaction (once) and run the operation in place, so it is atomic with\n * the rest of the caller's transaction and its locks last until commit.\n * - Inside a batch `$transaction([...])`: run in place; the `$transaction`\n * wrapper below prepended the context statement to the batch.\n * - Standalone: unchanged — session application_name tag, then the\n * operation in its own `SET LOCAL` transaction when RLS tagging is on.\n */\n const dispatch = async (\n params: { model: string; query: (args: unknown) => Promise<unknown>; __internalParams?: PrismaQueryInternalParams },\n wsCtx: WorkspaceContext,\n _operation: string,\n finalArgs: unknown\n ): Promise<unknown> => {\n // No tagging: nothing is set per operation, so every call runs in place\n // exactly as before (inside a caller transaction or not).\n if (!tagsTransactions) return params.query(finalArgs);\n const callerTransaction = getCallerTransaction(params.__internalParams);\n if (callerTransaction?.kind === 'itx') {\n return runOperationInCallerTransaction(rawPrismaForCallerTransactions, callerTransaction, wsCtx, fullConfig, () =>\n params.query(finalArgs)\n );\n }\n if (callerTransaction?.kind === 'batch') {\n return params.query(finalArgs);\n }\n if (fullConfig.enableApplicationNameTagging) {\n await maybeTagConnection(rawPrisma, wsCtx);\n }\n if (fullConfig.enableRlsGucTagging) {\n return runQueryWithRlsGuc(rawPrismaForContinuations, wsCtx, () => params.query(finalArgs));\n }\n return params.query(finalArgs);\n };\n\n /**\n * Raw SQL inside a caller's interactive transaction gets the same context, so\n * `SELECT … FOR UPDATE` fences and raw reads/writes see the caller's workspace\n * under FORCE RLS. Standalone raw SQL is unchanged (no context statement).\n */\n const rawOperation = async ({ args, query, __internalParams }: RawOperationHandlerParams): Promise<unknown> => {\n if (!tagsTransactions) return query(args);\n const callerTransaction = getCallerTransaction(__internalParams);\n if (callerTransaction?.kind !== 'itx') return query(args);\n const wsCtx = getWorkspaceContext();\n if (!wsCtx?.workspaceId) return query(args);\n return runOperationInCallerTransaction(rawPrismaForCallerTransactions, callerTransaction, wsCtx, fullConfig, () =>\n query(args)\n );\n };\n\n // Type assertion for Prisma client $extends\n const prismaClient = baseClient as { $extends: (args: unknown) => T };\n\n logger.info('[WorkspaceExtension] Workspace extension enabled', {\n populateContextJson: fullConfig.populateContextJson,\n populateCreatedBy: fullConfig.populateCreatedBy,\n populateUpdatedBy: fullConfig.populateUpdatedBy,\n populateTenantId: fullConfig.populateTenantId,\n enableReadIsolation: fullConfig.enableReadIsolation,\n enableDeleteIsolation: fullConfig.enableDeleteIsolation,\n enableUpdateWhereIsolation: fullConfig.enableUpdateWhereIsolation,\n strictMode: fullConfig.strictMode,\n excludeModels: fullConfig.excludeModels,\n excludeModelsFromReadIsolation: fullConfig.excludeModelsFromReadIsolation,\n allowedUnguardedOperations: fullConfig.allowedUnguardedOperations,\n enableApplicationNameTagging: fullConfig.enableApplicationNameTagging,\n enableRlsGucTagging: fullConfig.enableRlsGucTagging,\n });\n\n // Raw SQL hooks only matter when a context statement exists to apply.\n const rawOperationHooks = tagsTransactions\n ? {\n $queryRaw: rawOperation,\n $executeRaw: rawOperation,\n $queryRawUnsafe: rawOperation,\n $executeRawUnsafe: rawOperation,\n $queryRawTyped: rawOperation,\n }\n : {};\n\n const withQueryHooks = prismaClient.$extends({\n query: {\n ...rawOperationHooks,\n $allModels: {\n // ================================================================\n // WRITE OPERATIONS - inject workspaceId into data\n // ================================================================\n\n async create({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n data: Record<string, unknown>;\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n // Skip if model is excluded or injection is explicitly skipped\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'create', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n // Inject fields into data\n const injectedData = injectCreateFields(args.data, wsCtx, fullConfig);\n\n if (fullConfig.debug) {\n const injectedKeys = Object.keys(injectedData).filter((k) => !(k in args.data));\n if (injectedKeys.length > 0) {\n logger.debug(`[WorkspaceExtension] ${model}.create - injected: ${injectedKeys.join(', ')}`, {\n workspaceId: wsCtx.workspaceId,\n actorId: wsCtx.actorId,\n });\n }\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n data: injectedData,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'create', finalArgs);\n },\n\n async createMany({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n data: Record<string, unknown> | Record<string, unknown>[];\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'createMany', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n // Handle both single object and array\n const dataArray = Array.isArray(args.data) ? args.data : [args.data];\n const injectedData = dataArray.map((item) => injectCreateFields(item, wsCtx, fullConfig));\n\n const finalArgs = {\n ...stripSkipFlag(args),\n data: Array.isArray(args.data) ? injectedData : injectedData[0],\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'createMany', finalArgs);\n },\n\n async createManyAndReturn({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n data: Record<string, unknown> | Record<string, unknown>[];\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'createManyAndReturn', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const dataArray = Array.isArray(args.data) ? args.data : [args.data];\n const injectedData = dataArray.map((item) => injectCreateFields(item, wsCtx, fullConfig));\n\n const finalArgs = {\n ...stripSkipFlag(args),\n data: Array.isArray(args.data) ? injectedData : injectedData[0],\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'createManyAndReturn', finalArgs);\n },\n\n // ================================================================\n // UPDATE OPERATIONS - inject updatedBy into data + workspaceId into where\n // ================================================================\n\n async update({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n data: Record<string, unknown>;\n where?: Record<string, unknown>;\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'update', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedData = injectUpdateFields(args.data, wsCtx, fullConfig);\n\n // Inject workspaceId into where clause for update isolation\n let injectedWhere = args.where;\n if (fullConfig.enableUpdateWhereIsolation && !isExcludedFromReadIsolation(model, fullConfig)) {\n injectedWhere = injectWhereClause(args.where, wsCtx);\n }\n\n if (fullConfig.debug) {\n const injectedDataKeys = Object.keys(injectedData).filter((k) => !(k in args.data));\n const whereChanged = injectedWhere !== args.where;\n if (injectedDataKeys.length > 0 || whereChanged) {\n logger.debug(\n `[WorkspaceExtension] ${model}.update - injected data: ${injectedDataKeys.join(', ')}${whereChanged ? ', where: workspaceId' : ''}`\n );\n }\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n data: injectedData,\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'update', finalArgs);\n },\n\n async updateMany({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n data: Record<string, unknown>;\n where?: Record<string, unknown>;\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'updateMany', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedData = injectUpdateFields(args.data, wsCtx, fullConfig);\n\n // Inject workspaceId into where clause for update isolation\n let injectedWhere = args.where;\n if (fullConfig.enableUpdateWhereIsolation && !isExcludedFromReadIsolation(model, fullConfig)) {\n injectedWhere = injectWhereClause(args.where, wsCtx);\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n data: injectedData,\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'updateMany', finalArgs);\n },\n\n async upsert({\n model,\n args,\n query,\n __internalParams,\n }: ExtensionHandlerParams<{\n create: Record<string, unknown>;\n update: Record<string, unknown>;\n where?: Record<string, unknown>;\n _skipWorkspaceInjection?: boolean;\n [key: string]: unknown;\n }>) {\n if (fullConfig.excludeModels.includes(model) || args._skipWorkspaceInjection) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'upsert', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedCreate = injectCreateFields(args.create, wsCtx, fullConfig);\n const injectedUpdate = injectUpdateFields(args.update, wsCtx, fullConfig);\n\n // Inject workspaceId into where clause for upsert isolation\n let injectedWhere = args.where;\n if (fullConfig.enableUpdateWhereIsolation && !isExcludedFromReadIsolation(model, fullConfig)) {\n injectedWhere = injectWhereClause(args.where, wsCtx);\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n create: injectedCreate,\n update: injectedUpdate,\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'upsert', finalArgs);\n },\n\n // ================================================================\n // READ OPERATIONS - inject workspaceId into where clause\n // ================================================================\n\n async findMany({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'findMany', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.findMany - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'findMany', finalArgs);\n },\n\n async findFirst({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'findFirst', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.findFirst - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'findFirst', finalArgs);\n },\n\n async findFirstOrThrow({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'findFirstOrThrow', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.findFirstOrThrow - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'findFirstOrThrow', finalArgs);\n },\n\n async findUnique({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'findUnique', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n // For findUnique, the where clause uses unique fields.\n // We inject workspaceId only if the where clause is a plain object\n // (compound unique keys with workspaceId are common and already include it).\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.findUnique - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'findUnique', finalArgs);\n },\n\n async findUniqueOrThrow({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'findUniqueOrThrow', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.findUniqueOrThrow - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'findUniqueOrThrow', finalArgs);\n },\n\n async count({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'count', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.count - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'count', finalArgs);\n },\n\n async aggregate({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'aggregate', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.aggregate - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'aggregate', finalArgs);\n },\n\n async groupBy({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableReadIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'groupBy', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.groupBy - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'groupBy', finalArgs);\n },\n\n // ================================================================\n // DELETE OPERATIONS - inject workspaceId into where clause\n // ================================================================\n\n async delete({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableDeleteIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'delete', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.delete - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'delete', finalArgs);\n },\n\n async deleteMany({ model, args, query, __internalParams }: ExtensionHandlerParams<WhereArgs>) {\n if (\n !fullConfig.enableDeleteIsolation ||\n isExcludedFromReadIsolation(model, fullConfig) ||\n args._skipWorkspaceInjection\n ) {\n return query(stripSkipFlag(args));\n }\n\n const wsCtx = getWorkspaceContext();\n enforceStrictMode(model, 'deleteMany', wsCtx, fullConfig);\n if (!wsCtx?.workspaceId) {\n return query(args);\n }\n\n const injectedWhere = injectWhereClause(args.where, wsCtx);\n\n if (fullConfig.debug) {\n logger.debug(`[WorkspaceExtension] ${model}.deleteMany - injected workspaceId into where`, {\n workspaceId: wsCtx.workspaceId,\n });\n }\n\n const finalArgs = {\n ...stripSkipFlag(args),\n where: injectedWhere,\n };\n return dispatch({ model, query, __internalParams }, wsCtx, 'deleteMany', finalArgs);\n },\n },\n },\n });\n\n // Batch transactions: Prisma runs `$transaction([...])` members in one database\n // transaction, but an operation hook cannot add a statement to the batch. So\n // wrap `$transaction` itself and prepend the context statement; its result is\n // dropped so callers get exactly their own members' results. The function form\n // binds lazy consumption inside its callback; query hooks still apply RLS GUCs.\n // `$parent` is the client one extension layer down (the query-hooked client\n // above), so members and nested transactions keep every hook.\n const wrapped = withQueryHooks as unknown as { $extends: (args: unknown) => T };\n return wrapped.$extends({\n client: {\n $transaction(this: { $parent?: TransactionDelegate }, input: unknown, options?: unknown): Promise<unknown> {\n const parent = this.$parent;\n if (!parent) {\n throw new Error('[WorkspaceExtension] $transaction wrapper could not resolve its parent client.');\n }\n if (Array.isArray(input)) {\n const wsCtx = getWorkspaceContext();\n const statement =\n tagsTransactions && wsCtx?.workspaceId ? buildTransactionContextStatement(wsCtx, fullConfig) : undefined;\n if (statement) {\n const setContext = rawPrismaForCallerTransactions.$executeRawUnsafe(statement.sql, ...statement.params);\n return parent\n .$transaction([setContext, ...input], options)\n .then((results) => (Array.isArray(results) ? results.slice(1) : results));\n }\n }\n // The native delegate reads the final client's extension chain. Calling\n // it on $parent would silently omit later graph/audit query hooks.\n if (typeof input === 'function') {\n // Keep lazy returned operations in their originating callback context,\n // including Bun thenable assimilation after an awaited earlier query.\n const callback = input as (tx: object) => Promise<unknown>;\n return transactionDelegate.call(\n this,\n async (tx: object) => {\n const scope = { active: true };\n try {\n return await callback(bindTransactionContext(tx, scope, getWorkspaceContext));\n } finally {\n scope.active = false;\n }\n },\n options\n );\n }\n return transactionDelegate.call(this, input, options);\n },\n },\n });\n}\n"],"mappings":";;;;AAMA,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,YAAY,GAAqB,GAA8B;CACtE,OAAO,cAAc,OAAO,UAAU,EAAE,WAAW,EAAE,MAAM;AAC7D;;;;;;;AAQA,SAAgB,uBACd,QACA,OACA,qBACG;CACH,MAAM,4BAAY,IAAI,QAAwB;CAC9C,SAAS,cAAc,OAAyB;EAC9C,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,QAAQ,IAAI,OAAO,OAAO,WAAW,MAAM,iBAAiB,OAAO;EAC9G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