@burdenoff/be-sdk 2026.1130.3 → 2026.1201.2
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/README.md +6 -1
- package/dist/context/index.js +7 -2
- package/dist/context/index.js.map +1 -1
- package/dist/files/index.d.ts +2 -2
- package/dist/files/index.js +2 -2
- package/dist/{files-h5U-D2AF.js → files-BISdM0fh.js} +188 -28
- package/dist/files-BISdM0fh.js.map +1 -0
- package/dist/{bun-runtime-metrics-CPy5D6NT.js → incoming-request-span-DCou42Il.js} +56 -2
- package/dist/incoming-request-span-DCou42Il.js.map +1 -0
- package/dist/{index-8pUSoT85.d.ts → index-ieSQpD9r.d.ts} +26 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/prisma/index.js +2 -2
- package/dist/{prisma-Bo-C0XUv.js → prisma-D0f-THMv.js} +2 -2
- package/dist/{prisma-Bo-C0XUv.js.map → prisma-D0f-THMv.js.map} +1 -1
- package/dist/{sdk-7TBR987n.js → sdk-Oooulm2n.js} +22 -6
- package/dist/sdk-Oooulm2n.js.map +1 -0
- package/dist/server/index.js +5 -5
- package/dist/server/index.js.map +1 -1
- package/dist/{stub-DNkzpQvR.js → stub-CmVOE6ql.js} +2 -2
- package/dist/{stub-DNkzpQvR.js.map → stub-CmVOE6ql.js.map} +1 -1
- package/dist/telemetry/index.d.ts +40 -2
- package/dist/telemetry/index.js +3 -3
- package/dist/telemetry/index.js.map +1 -1
- package/dist/tracker/index.js +2 -2
- package/dist/{tracker-CDVYIoCb.js → tracker-CNF8TRpk.js} +2 -2
- package/dist/{tracker-CDVYIoCb.js.map → tracker-CNF8TRpk.js.map} +1 -1
- package/dist/{workspace-extension-BcMPoGWr.js → workspace-extension-feJYFO9e.js} +41 -8
- package/dist/workspace-extension-feJYFO9e.js.map +1 -0
- package/package.json +1 -1
- package/dist/bun-runtime-metrics-CPy5D6NT.js.map +0 -1
- package/dist/files-h5U-D2AF.js.map +0 -1
- package/dist/sdk-7TBR987n.js.map +0 -1
- package/dist/workspace-extension-BcMPoGWr.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracker-CDVYIoCb.js","names":[],"sources":["../src/tracker/agent-activity.ts","../src/tracker/index.ts"],"sourcesContent":["/**\n * AI-agent activity (BOFF-9684)\n *\n * Platform-wide activity actions for what an AI agent does, and a helper that records them with\n * the agent as an `app` actor. The audit trail can then separate agent actions from the human\n * actions around them (ISO/IEC 42001 Annex A.9 evidence) and link each one back to the person\n * who started the run (`onBehalfOf`).\n *\n * The action names follow the platform taxonomy `<domain>.<resource>.<verb>` and are shared by\n * every product that runs agents; the product is identified by `productId`.\n *\n * @example\n * ```ts\n * import { AGENT_ACTIVITY_ACTIONS, trackAgentActivity } from '@burdenoff/be-sdk/tracker';\n *\n * await trackAgentActivity({\n * action: AGENT_ACTIVITY_ACTIONS.TOOL_CALLED,\n * agentId: agent.id,\n * workspaceId,\n * onBehalfOf: userId,\n * productId: 'botmanor',\n * metadata: { toolName: 'search' },\n * });\n * ```\n *\n * @module tracker/agent-activity\n * @category Tracking\n */\nimport { createExplicitActivityScope, runInExplicitActivityScope } from '../activity/explicit-activity-scope.js';\nimport { trackOperation } from './stub.js';\n\n/** Activity actions for AI-agent behaviour. */\nexport const AGENT_ACTIVITY_ACTIONS = Object.freeze({\n /** An agent run (one turn) finished and produced a response. */\n RUN_COMPLETED: 'agent.run.completed',\n /** An agent run failed before producing a response. */\n RUN_FAILED: 'agent.run.failed',\n /** The agent called a tool (MCP or similar). `success: false` when the call failed. */\n TOOL_CALLED: 'agent.tool.called',\n /** The agent delegated a sub-task to another agent. */\n DELEGATION_SENT: 'agent.delegation.sent',\n /** A governance policy refused something the agent run attempted (input, output, tool, model, budget, rate). */\n POLICY_BLOCKED: 'agent.policy.blocked',\n} as const);\n\nexport type AgentActivityAction = (typeof AGENT_ACTIVITY_ACTIONS)[keyof typeof AGENT_ACTIVITY_ACTIONS];\n\n/** Default `resourceType` of agent activity rows; `resourceId` defaults to the agent id. */\nexport const AGENT_ACTIVITY_RESOURCE_TYPE = 'agent';\n\nconst FAILURE_ACTIONS: ReadonlySet<AgentActivityAction> = new Set<AgentActivityAction>([\n AGENT_ACTIVITY_ACTIONS.RUN_FAILED,\n AGENT_ACTIVITY_ACTIONS.POLICY_BLOCKED,\n]);\n\nexport interface AgentActivityOptions {\n action: AgentActivityAction;\n /** The agent that acted. Recorded as the row's actor (`userId`) with `actorType: 'app'`. */\n agentId: string;\n workspaceId: string;\n /** The human who started the run, when there is one. */\n onBehalfOf?: string;\n /** Product that runs the agent, e.g. `botmanor`. */\n productId?: string;\n /** Defaults to false for RUN_FAILED and POLICY_BLOCKED, true otherwise. */\n success?: boolean;\n errorMessage?: string;\n description?: string;\n /** Defaults to `AGENT_ACTIVITY_RESOURCE_TYPE`. */\n resourceType?: string;\n /** Defaults to `agentId`. */\n resourceId?: string;\n metadata?: Record<string, unknown>;\n /** Stable idempotency key, only for callers that may replay the same event. */\n dedupeKey?: string;\n}\n\n/**\n * Record one AI-agent activity row, attributed to the agent as an `app` actor.\n *\n * Fire-and-forget like `trackOperation`: it never throws for a delivery failure and never blocks\n * on the activity service. It runs in its own explicit-activity scope, so recording what the\n * agent did does not suppress the mutation-audit row of the human request that started the run.\n */\nexport function trackAgentActivity(options: AgentActivityOptions): Promise<boolean> {\n const success = options.success ?? !FAILURE_ACTIONS.has(options.action);\n return runInExplicitActivityScope(createExplicitActivityScope(), () =>\n trackOperation({\n operationName: options.action,\n userId: options.agentId,\n actorType: 'app',\n ...(options.onBehalfOf ? { onBehalfOf: options.onBehalfOf } : {}),\n workspaceId: options.workspaceId,\n ...(options.productId ? { productId: options.productId } : {}),\n success,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n activityOptions: {\n enabled: true,\n activityType: options.action,\n description: options.description ?? `Agent ${options.agentId}: ${options.action}`,\n workspaceId: options.workspaceId,\n resourceType: options.resourceType ?? AGENT_ACTIVITY_RESOURCE_TYPE,\n resourceId: options.resourceId ?? options.agentId,\n metadata: { ...options.metadata, agentId: options.agentId },\n ...(options.dedupeKey ? { dedupeKey: options.dedupeKey } : {}),\n },\n })\n );\n}\n","/**\n * Unified Tracker Module\n * Aggregates RBAC + Activity + Usage + Notifications in single function call\n * This is the MOST IMPORTANT module that products should use for most operations\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { PermissionDeniedError, QuotaExceededError, ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\nimport { RBACModule, type CheckPermissionOptions } from '../rbac/index.js';\nimport { ActivityModule, ActivityType, ActivityStatus, ActivitySeverity } from '../activity/index.js';\nimport { UsageModule, type UsageMetricType } from '../usage/index.js';\nimport { NotificationsModule, NotificationType } from '../notifications/index.js';\n\nexport interface TrackOptions {\n /** User performing the action */\n userId: string;\n /** Action being performed */\n action: string;\n /** Resource type */\n resourceType: string;\n /** Optional resource ID */\n resourceId?: string;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n /** Project context */\n projectId?: string;\n\n /** RBAC options */\n rbac?: {\n /** Check permission before executing (default: true) */\n enabled?: boolean;\n /** Custom permission action (defaults to action parameter) */\n permissionAction?: string;\n };\n\n /** Activity tracking options */\n activity?: {\n /** Enable activity tracking (default: true) */\n enabled?: boolean;\n /** Activity type (auto-inferred if not provided) */\n activityType?: ActivityType;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** IP address */\n ipAddress?: string;\n /** User agent */\n userAgent?: string;\n /** Severity level */\n severity?: ActivitySeverity;\n };\n\n /**\n * Usage tracking options.\n *\n * The tracker meters a workspace quota only when `quotaName` is set: it checks capacity\n * with the owner's `checkWorkspaceQuota` (for positive amounts) and records the amount\n * with `trackUsage`. Without a `quotaName` the usage step is skipped. Mutations whose\n * schema carries a gateway `@usage` directive are already metered by the gateway and\n * should not set `quotaName` here, or the quota is charged twice.\n */\n usage?: {\n /** Enable usage tracking (default: true) */\n enabled?: boolean;\n /** Workspace quota to charge, for example `platform.projects.created`. */\n quotaName?: string;\n /** Product that owns the quota. Defaults to the SDK context's `productId`. */\n productId?: string;\n /** Description stored on the usage record. Defaults to `<action> <resourceType>`. */\n description?: string;\n /**\n * Amount to record (default: 1). A negative amount releases usage, for example on\n * delete; the quota check is skipped for it.\n */\n amount?: number;\n /** Check quota before recording a positive amount (default: true) */\n checkQuota?: boolean;\n /**\n * Legacy metric name. The workspace usage owner has no metric types, so a metric type\n * without a `quotaName` is not metered by the tracker.\n */\n metricType?: UsageMetricType;\n /** Legacy entity type. Workspace quotas are always charged to the workspace. */\n entityType?: 'user' | 'workspace' | 'organization';\n };\n\n /** Notification options */\n notification?: {\n /** Send notification on success */\n onSuccess?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n /** Send notification on failure */\n onFailure?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n };\n}\n\n/** A usage step that meters a named workspace quota. */\ninterface ResolvedUsage {\n quotaName: string;\n amount: number;\n workspaceId: string;\n checkQuota: boolean;\n}\n\nexport interface TrackResult {\n success: boolean;\n /** Permission check result */\n permissionGranted: boolean;\n /** Quota check result (if quota checking enabled) */\n quotaAvailable?: boolean;\n quotaRemaining?: number;\n /** Activity record ID */\n activityId?: string;\n /** True when the usage step recorded the amount with the owner */\n usageTracked?: boolean;\n /**\n * @deprecated The owner's `trackUsage` returns `Boolean!` and no record id, so this is\n * never set. Read `usageTracked` instead.\n */\n usageRecordId?: string;\n /** Notification IDs sent */\n notificationIds?: string[];\n /** Error if operation failed */\n error?: {\n type: 'permission' | 'quota' | 'validation' | 'unknown';\n message: string;\n details?: Record<string, unknown>;\n };\n /** Operation duration in milliseconds */\n duration: number;\n}\n\n/**\n * Unified Tracker Module\n *\n * The primary module products should use for tracking operations.\n * Automatically handles RBAC checks, activity logging, usage tracking, and notifications.\n *\n * @example\n * ```typescript\n * const result = await sdk.tracker.track({\n * userId: 'user123',\n * action: 'create_project',\n * resourceType: 'project',\n * workspaceId: 'ws123',\n * usage: {\n * quotaName: 'myproduct.projects.count',\n * productId: 'myproduct',\n * amount: 1,\n * checkQuota: true,\n * },\n * notification: {\n * onSuccess: {\n * title: 'Project Created',\n * message: 'Your project has been created successfully',\n * },\n * },\n * });\n *\n * if (!result.success) {\n * // Handle error\n * }\n * ```\n */\nexport class TrackerModule {\n private rbac: RBACModule;\n private activity: ActivityModule;\n private usage: UsageModule;\n private notifications: NotificationsModule;\n\n constructor(\n client: BurdenoffGraphQLClient,\n private context: SDKContext = {}\n ) {\n this.rbac = new RBACModule(client, context);\n this.activity = new ActivityModule(client, context);\n this.usage = new UsageModule(client, context);\n this.notifications = new NotificationsModule(client, context);\n }\n\n /**\n * Track operation with RBAC, Activity, Usage, and Notifications\n * This is the primary method products should use\n */\n public async track(options: TrackOptions): Promise<TrackResult> {\n const startTime = Date.now();\n const result: TrackResult = {\n success: false,\n permissionGranted: false,\n duration: 0,\n };\n\n try {\n // Validate required fields\n this.validateOptions(options);\n\n // Step 1: Check RBAC permission (if enabled)\n if (options.rbac?.enabled !== false) {\n await this.checkPermission(options, result);\n if (!result.permissionGranted) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n } else {\n result.permissionGranted = true;\n }\n\n // Steps 2 and 3: check quota, then record usage (only for a named workspace quota)\n const usage = this.resolveUsage(options);\n if (usage) {\n let quotaAssignmentId: string | undefined;\n if (usage.checkQuota) {\n quotaAssignmentId = await this.checkQuota(options, usage, result);\n if (result.quotaAvailable === false) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n }\n await this.trackUsage(options, usage, quotaAssignmentId, result);\n }\n\n // Step 4: Log successful activity (if enabled)\n if (options.activity?.enabled !== false) {\n await this.logSuccessActivity(options, result, startTime);\n }\n\n // Step 5: Send success notification (if configured)\n if (options.notification?.onSuccess) {\n await this.sendSuccessNotification(options, result);\n }\n\n result.success = true;\n result.duration = Date.now() - startTime;\n\n logger.info('[Tracker] Operation tracked successfully', {\n action: options.action,\n duration: result.duration,\n });\n\n return result;\n } catch (error) {\n result.duration = Date.now() - startTime;\n result.success = false;\n\n // Categorize error\n if (error instanceof PermissionDeniedError) {\n result.error = {\n type: 'permission',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof QuotaExceededError) {\n result.error = {\n type: 'quota',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof ValidationError) {\n result.error = {\n type: 'validation',\n message: error.message,\n details: error.details,\n };\n } else {\n result.error = {\n type: 'unknown',\n message: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n\n // Log failed activity\n await this.logFailedActivity(options, result, startTime);\n\n // Send failure notification (if configured)\n if (options.notification?.onFailure) {\n await this.sendFailureNotification(options, result);\n }\n\n logger.error('[Tracker] Operation tracking failed', {\n action: options.action,\n error: result.error,\n duration: result.duration,\n });\n\n return result;\n }\n }\n\n /**\n * Track operation and throw on failure\n * Convenience method that throws errors instead of returning them in result\n */\n public async trackOrThrow(options: TrackOptions): Promise<TrackResult> {\n const result = await this.track(options);\n\n if (!result.success && result.error) {\n const errorMessage = result.error.message;\n const errorDetails = result.error.details;\n\n switch (result.error.type) {\n case 'permission':\n throw new PermissionDeniedError(errorMessage, errorDetails);\n case 'quota':\n throw new QuotaExceededError(errorMessage, errorDetails);\n case 'validation':\n throw new ValidationError(errorMessage, errorDetails);\n default:\n throw new Error(errorMessage);\n }\n }\n\n return result;\n }\n\n /**\n * Simplified track method for common operations.\n * The trailing metric type is accepted for source compatibility and is not metered.\n */\n public async trackSimple(\n userId: string,\n action: string,\n resourceType: string,\n resourceId?: string,\n _metricType?: UsageMetricType\n ): Promise<boolean> {\n // A metric type has no workspace quota on the owner, so trackSimple never meters usage.\n // Call track() with `usage.quotaName` to charge a quota.\n const result = await this.track({\n userId,\n action,\n resourceType,\n resourceId,\n workspaceId: this.context.workspaceId,\n usage: { enabled: false },\n });\n\n return result.success;\n }\n\n /**\n * Validate tracking options\n */\n private validateOptions(options: TrackOptions): void {\n if (!options.userId) {\n throw new ValidationError('User ID is required');\n }\n\n if (!options.action) {\n throw new ValidationError('Action is required');\n }\n\n if (!options.resourceType) {\n throw new ValidationError('Resource type is required');\n }\n }\n\n /**\n * Check RBAC permission\n */\n private async checkPermission(options: TrackOptions, result: TrackResult): Promise<void> {\n const permissionOptions: CheckPermissionOptions = {\n userId: options.userId,\n action: options.rbac?.permissionAction || options.action,\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n workspaceId: options.workspaceId,\n };\n\n const hasPermission = await this.rbac.checkPermission(permissionOptions);\n result.permissionGranted = hasPermission;\n\n if (!hasPermission) {\n result.error = {\n type: 'permission',\n message: 'Permission denied',\n details: permissionOptions as unknown as Record<string, unknown>,\n };\n }\n }\n\n /**\n * Resolve the usage step for an operation, or null when nothing is metered: usage is\n * disabled, or no workspace quota is named (a legacy `metricType` alone has no owner\n * quota to charge).\n */\n private resolveUsage(options: TrackOptions): ResolvedUsage | null {\n const usage = options.usage;\n if (!usage || usage.enabled === false) {\n return null;\n }\n const quotaName = usage.quotaName?.trim();\n if (!quotaName) {\n if (usage.metricType) {\n logger.debug('[Tracker] Usage step skipped: no quotaName for legacy metricType', {\n action: options.action,\n metricType: usage.metricType,\n });\n }\n return null;\n }\n const amount = usage.amount ?? 1;\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount === 0) {\n throw new ValidationError('Usage amount must be a finite, non-zero number');\n }\n const workspaceId = options.workspaceId ?? this.context.workspaceId;\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required to track workspace quota usage');\n }\n return {\n quotaName,\n amount,\n workspaceId,\n // Only consumption is gated; a release (negative amount) must always go through.\n checkQuota: usage.checkQuota !== false && amount > 0,\n };\n }\n\n /**\n * Check workspace quota capacity. Returns the assignment to charge when one exists.\n */\n private async checkQuota(\n options: TrackOptions,\n usage: ResolvedUsage,\n result: TrackResult\n ): Promise<string | undefined> {\n const quotaCheck = await this.usage.checkWorkspaceQuota({\n quotaName: usage.quotaName,\n amount: usage.amount,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n });\n\n result.quotaAvailable = quotaCheck.allowed;\n result.quotaRemaining = quotaCheck.limitLeft ?? undefined;\n\n if (!quotaCheck.allowed) {\n const notProvisioned = quotaCheck.assignmentId === null;\n result.error = {\n type: 'quota',\n message: notProvisioned\n ? `Quota ${usage.quotaName} is not included in this workspace's plan`\n : 'Quota exceeded',\n details: {\n quotaName: usage.quotaName,\n requestedAmount: usage.amount,\n limitLeft: quotaCheck.limitLeft,\n notProvisioned,\n },\n };\n }\n\n return quotaCheck.assignmentId ?? undefined;\n }\n\n /**\n * Record workspace quota usage with the owner.\n */\n private async trackUsage(\n options: TrackOptions,\n usage: ResolvedUsage,\n quotaAssignmentId: string | undefined,\n result: TrackResult\n ): Promise<void> {\n result.usageTracked = await this.usage.trackUsage({\n quotaName: usage.quotaName,\n productId: options.usage?.productId,\n amount: usage.amount,\n description: options.usage?.description?.trim() || `${options.action} ${options.resourceType}`,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n quotaAssignmentId,\n metadata: {\n action: options.action,\n resourceType: options.resourceType,\n ...(options.resourceId ? { resourceId: options.resourceId } : {}),\n },\n });\n }\n\n /**\n * Log successful activity\n */\n private async logSuccessActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.SUCCESS,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: options.activity?.severity || ActivitySeverity.LOW,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n }\n\n /**\n * Log failed activity\n */\n private async logFailedActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n if (options.activity?.enabled === false) {\n return;\n }\n\n try {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.FAILURE,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: ActivitySeverity.HIGH,\n errorMessage: result.error?.message,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n } catch (error) {\n logger.error('[Tracker] Failed to log activity', { error });\n }\n }\n\n /**\n * Send success notification\n */\n private async sendSuccessNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onSuccess) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onSuccess.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onSuccess.title,\n message: options.notification.onSuccess.message,\n type: options.notification.onSuccess.type || NotificationType.SUCCESS,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send success notification', { error });\n }\n }\n\n /**\n * Send failure notification\n */\n private async sendFailureNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onFailure) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onFailure.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onFailure.title,\n message: options.notification.onFailure.message,\n type: options.notification.onFailure.type || NotificationType.ERROR,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send failure notification', { error });\n }\n }\n\n /**\n * Infer activity type from action\n */\n private inferActivityType(action: string): ActivityType {\n const actionLower = action.toLowerCase();\n\n if (actionLower.includes('create') || actionLower.includes('add')) return ActivityType.CREATE;\n if (actionLower.includes('update') || actionLower.includes('edit')) return ActivityType.UPDATE;\n if (actionLower.includes('delete') || actionLower.includes('remove')) return ActivityType.DELETE;\n if (actionLower.includes('read') || actionLower.includes('view')) return ActivityType.READ;\n if (actionLower.includes('login')) return ActivityType.LOGIN;\n if (actionLower.includes('logout')) return ActivityType.LOGOUT;\n if (actionLower.includes('export')) return ActivityType.EXPORT;\n if (actionLower.includes('import')) return ActivityType.IMPORT;\n if (actionLower.includes('share')) return ActivityType.SHARE;\n if (actionLower.includes('download')) return ActivityType.DOWNLOAD;\n if (actionLower.includes('upload')) return ActivityType.UPLOAD;\n\n return ActivityType.CUSTOM;\n }\n\n /**\n * Batch track multiple operations\n */\n public async trackBatch(operations: TrackOptions[]): Promise<TrackResult[]> {\n logger.debug('[Tracker] Batch tracking operations', { count: operations.length });\n\n const results = await Promise.all(operations.map((op) => this.track(op)));\n\n logger.info('[Tracker] Batch tracking completed', {\n total: results.length,\n successful: results.filter((r) => r.success).length,\n failed: results.filter((r) => !r.success).length,\n });\n\n return results;\n }\n}\n\n// Export stub implementation for services that don't need full tracking\nexport {\n trackOperation,\n createProductTracker,\n UnifiedTrackerStub,\n trackerStub,\n UNIFIED_TRACKER_CONSTANTS,\n} from './stub.js';\nexport { isTrackedActorType, resolveAssistantSession } from './stub.js';\n// Assistant-session attribution on activity rows (BOFF-9649)\nexport { AI_ASSISTANT_ACTOR_ORIGIN } from '../activity/assistant-session.js';\nexport type { ActorOrigin, AssistantSessionAttribution } from '../activity/assistant-session.js';\nexport type {\n TrackingEvent,\n RbacCheckOptions,\n UsageTrackingOptions,\n ActivityTrackingOptions,\n UnifiedTrackingOptions,\n ProductTracker,\n TrackedActorType,\n} from './stub.js';\n\n// AI-agent activity actions and recorder (BOFF-9684)\nexport { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, trackAgentActivity } from './agent-activity.js';\nexport type { AgentActivityAction, AgentActivityOptions } from './agent-activity.js';\n\n// Opt a resolver out of the mutation-audit backstop row (see server/mutation-audit.ts)\nexport { suppressMutationAudit } from '../activity/explicit-activity-scope.js';\n\n// Re-export UsageMetricType from usage module for convenience\nexport { UsageMetricType } from '../usage/index.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,yBAAyB,OAAO,OAAO;;CAElD,eAAe;;CAEf,YAAY;;CAEZ,aAAa;;CAEb,iBAAiB;;CAEjB,gBAAgB;AAClB,CAAU;;AAKV,MAAa,+BAA+B;AAE5C,MAAM,kCAAoD,IAAI,IAAyB,CACrF,uBAAuB,YACvB,uBAAuB,cACzB,CAAC;;;;;;;;AA+BD,SAAgB,mBAAmB,SAAiD;CAClF,MAAM,UAAU,QAAQ,WAAW,CAAC,gBAAgB,IAAI,QAAQ,MAAM;CACtE,OAAO,2BAA2B,4BAA4B,SAC5D,eAAe;EACb,eAAe,QAAQ;EACvB,QAAQ,QAAQ;EAChB,WAAW;EACX,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;EAC/D,aAAa,QAAQ;EACrB,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC5D;EACA,GAAI,QAAQ,eAAe,EAAE,cAAc,QAAQ,aAAa,IAAI,CAAC;EACrE,iBAAiB;GACf,SAAS;GACT,cAAc,QAAQ;GACtB,aAAa,QAAQ,eAAe,SAAS,QAAQ,QAAQ,IAAI,QAAQ;GACzE,aAAa,QAAQ;GACrB,cAAc,QAAQ;GACtB,YAAY,QAAQ,cAAc,QAAQ;GAC1C,UAAU;IAAE,GAAG,QAAQ;IAAU,SAAS,QAAQ;GAAQ;GAC1D,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC9D;CACF,CAAC,CACH;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACsEA,IAAa,gBAAb,MAA2B;CAQf;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CAAC;EAED,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"tracker-CNF8TRpk.js","names":[],"sources":["../src/tracker/agent-activity.ts","../src/tracker/index.ts"],"sourcesContent":["/**\n * AI-agent activity (BOFF-9684)\n *\n * Platform-wide activity actions for what an AI agent does, and a helper that records them with\n * the agent as an `app` actor. The audit trail can then separate agent actions from the human\n * actions around them (ISO/IEC 42001 Annex A.9 evidence) and link each one back to the person\n * who started the run (`onBehalfOf`).\n *\n * The action names follow the platform taxonomy `<domain>.<resource>.<verb>` and are shared by\n * every product that runs agents; the product is identified by `productId`.\n *\n * @example\n * ```ts\n * import { AGENT_ACTIVITY_ACTIONS, trackAgentActivity } from '@burdenoff/be-sdk/tracker';\n *\n * await trackAgentActivity({\n * action: AGENT_ACTIVITY_ACTIONS.TOOL_CALLED,\n * agentId: agent.id,\n * workspaceId,\n * onBehalfOf: userId,\n * productId: 'botmanor',\n * metadata: { toolName: 'search' },\n * });\n * ```\n *\n * @module tracker/agent-activity\n * @category Tracking\n */\nimport { createExplicitActivityScope, runInExplicitActivityScope } from '../activity/explicit-activity-scope.js';\nimport { trackOperation } from './stub.js';\n\n/** Activity actions for AI-agent behaviour. */\nexport const AGENT_ACTIVITY_ACTIONS = Object.freeze({\n /** An agent run (one turn) finished and produced a response. */\n RUN_COMPLETED: 'agent.run.completed',\n /** An agent run failed before producing a response. */\n RUN_FAILED: 'agent.run.failed',\n /** The agent called a tool (MCP or similar). `success: false` when the call failed. */\n TOOL_CALLED: 'agent.tool.called',\n /** The agent delegated a sub-task to another agent. */\n DELEGATION_SENT: 'agent.delegation.sent',\n /** A governance policy refused something the agent run attempted (input, output, tool, model, budget, rate). */\n POLICY_BLOCKED: 'agent.policy.blocked',\n} as const);\n\nexport type AgentActivityAction = (typeof AGENT_ACTIVITY_ACTIONS)[keyof typeof AGENT_ACTIVITY_ACTIONS];\n\n/** Default `resourceType` of agent activity rows; `resourceId` defaults to the agent id. */\nexport const AGENT_ACTIVITY_RESOURCE_TYPE = 'agent';\n\nconst FAILURE_ACTIONS: ReadonlySet<AgentActivityAction> = new Set<AgentActivityAction>([\n AGENT_ACTIVITY_ACTIONS.RUN_FAILED,\n AGENT_ACTIVITY_ACTIONS.POLICY_BLOCKED,\n]);\n\nexport interface AgentActivityOptions {\n action: AgentActivityAction;\n /** The agent that acted. Recorded as the row's actor (`userId`) with `actorType: 'app'`. */\n agentId: string;\n workspaceId: string;\n /** The human who started the run, when there is one. */\n onBehalfOf?: string;\n /** Product that runs the agent, e.g. `botmanor`. */\n productId?: string;\n /** Defaults to false for RUN_FAILED and POLICY_BLOCKED, true otherwise. */\n success?: boolean;\n errorMessage?: string;\n description?: string;\n /** Defaults to `AGENT_ACTIVITY_RESOURCE_TYPE`. */\n resourceType?: string;\n /** Defaults to `agentId`. */\n resourceId?: string;\n metadata?: Record<string, unknown>;\n /** Stable idempotency key, only for callers that may replay the same event. */\n dedupeKey?: string;\n}\n\n/**\n * Record one AI-agent activity row, attributed to the agent as an `app` actor.\n *\n * Fire-and-forget like `trackOperation`: it never throws for a delivery failure and never blocks\n * on the activity service. It runs in its own explicit-activity scope, so recording what the\n * agent did does not suppress the mutation-audit row of the human request that started the run.\n */\nexport function trackAgentActivity(options: AgentActivityOptions): Promise<boolean> {\n const success = options.success ?? !FAILURE_ACTIONS.has(options.action);\n return runInExplicitActivityScope(createExplicitActivityScope(), () =>\n trackOperation({\n operationName: options.action,\n userId: options.agentId,\n actorType: 'app',\n ...(options.onBehalfOf ? { onBehalfOf: options.onBehalfOf } : {}),\n workspaceId: options.workspaceId,\n ...(options.productId ? { productId: options.productId } : {}),\n success,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n activityOptions: {\n enabled: true,\n activityType: options.action,\n description: options.description ?? `Agent ${options.agentId}: ${options.action}`,\n workspaceId: options.workspaceId,\n resourceType: options.resourceType ?? AGENT_ACTIVITY_RESOURCE_TYPE,\n resourceId: options.resourceId ?? options.agentId,\n metadata: { ...options.metadata, agentId: options.agentId },\n ...(options.dedupeKey ? { dedupeKey: options.dedupeKey } : {}),\n },\n })\n );\n}\n","/**\n * Unified Tracker Module\n * Aggregates RBAC + Activity + Usage + Notifications in single function call\n * This is the MOST IMPORTANT module that products should use for most operations\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { PermissionDeniedError, QuotaExceededError, ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\nimport { RBACModule, type CheckPermissionOptions } from '../rbac/index.js';\nimport { ActivityModule, ActivityType, ActivityStatus, ActivitySeverity } from '../activity/index.js';\nimport { UsageModule, type UsageMetricType } from '../usage/index.js';\nimport { NotificationsModule, NotificationType } from '../notifications/index.js';\n\nexport interface TrackOptions {\n /** User performing the action */\n userId: string;\n /** Action being performed */\n action: string;\n /** Resource type */\n resourceType: string;\n /** Optional resource ID */\n resourceId?: string;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n /** Project context */\n projectId?: string;\n\n /** RBAC options */\n rbac?: {\n /** Check permission before executing (default: true) */\n enabled?: boolean;\n /** Custom permission action (defaults to action parameter) */\n permissionAction?: string;\n };\n\n /** Activity tracking options */\n activity?: {\n /** Enable activity tracking (default: true) */\n enabled?: boolean;\n /** Activity type (auto-inferred if not provided) */\n activityType?: ActivityType;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** IP address */\n ipAddress?: string;\n /** User agent */\n userAgent?: string;\n /** Severity level */\n severity?: ActivitySeverity;\n };\n\n /**\n * Usage tracking options.\n *\n * The tracker meters a workspace quota only when `quotaName` is set: it checks capacity\n * with the owner's `checkWorkspaceQuota` (for positive amounts) and records the amount\n * with `trackUsage`. Without a `quotaName` the usage step is skipped. Mutations whose\n * schema carries a gateway `@usage` directive are already metered by the gateway and\n * should not set `quotaName` here, or the quota is charged twice.\n */\n usage?: {\n /** Enable usage tracking (default: true) */\n enabled?: boolean;\n /** Workspace quota to charge, for example `platform.projects.created`. */\n quotaName?: string;\n /** Product that owns the quota. Defaults to the SDK context's `productId`. */\n productId?: string;\n /** Description stored on the usage record. Defaults to `<action> <resourceType>`. */\n description?: string;\n /**\n * Amount to record (default: 1). A negative amount releases usage, for example on\n * delete; the quota check is skipped for it.\n */\n amount?: number;\n /** Check quota before recording a positive amount (default: true) */\n checkQuota?: boolean;\n /**\n * Legacy metric name. The workspace usage owner has no metric types, so a metric type\n * without a `quotaName` is not metered by the tracker.\n */\n metricType?: UsageMetricType;\n /** Legacy entity type. Workspace quotas are always charged to the workspace. */\n entityType?: 'user' | 'workspace' | 'organization';\n };\n\n /** Notification options */\n notification?: {\n /** Send notification on success */\n onSuccess?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n /** Send notification on failure */\n onFailure?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n };\n}\n\n/** A usage step that meters a named workspace quota. */\ninterface ResolvedUsage {\n quotaName: string;\n amount: number;\n workspaceId: string;\n checkQuota: boolean;\n}\n\nexport interface TrackResult {\n success: boolean;\n /** Permission check result */\n permissionGranted: boolean;\n /** Quota check result (if quota checking enabled) */\n quotaAvailable?: boolean;\n quotaRemaining?: number;\n /** Activity record ID */\n activityId?: string;\n /** True when the usage step recorded the amount with the owner */\n usageTracked?: boolean;\n /**\n * @deprecated The owner's `trackUsage` returns `Boolean!` and no record id, so this is\n * never set. Read `usageTracked` instead.\n */\n usageRecordId?: string;\n /** Notification IDs sent */\n notificationIds?: string[];\n /** Error if operation failed */\n error?: {\n type: 'permission' | 'quota' | 'validation' | 'unknown';\n message: string;\n details?: Record<string, unknown>;\n };\n /** Operation duration in milliseconds */\n duration: number;\n}\n\n/**\n * Unified Tracker Module\n *\n * The primary module products should use for tracking operations.\n * Automatically handles RBAC checks, activity logging, usage tracking, and notifications.\n *\n * @example\n * ```typescript\n * const result = await sdk.tracker.track({\n * userId: 'user123',\n * action: 'create_project',\n * resourceType: 'project',\n * workspaceId: 'ws123',\n * usage: {\n * quotaName: 'myproduct.projects.count',\n * productId: 'myproduct',\n * amount: 1,\n * checkQuota: true,\n * },\n * notification: {\n * onSuccess: {\n * title: 'Project Created',\n * message: 'Your project has been created successfully',\n * },\n * },\n * });\n *\n * if (!result.success) {\n * // Handle error\n * }\n * ```\n */\nexport class TrackerModule {\n private rbac: RBACModule;\n private activity: ActivityModule;\n private usage: UsageModule;\n private notifications: NotificationsModule;\n\n constructor(\n client: BurdenoffGraphQLClient,\n private context: SDKContext = {}\n ) {\n this.rbac = new RBACModule(client, context);\n this.activity = new ActivityModule(client, context);\n this.usage = new UsageModule(client, context);\n this.notifications = new NotificationsModule(client, context);\n }\n\n /**\n * Track operation with RBAC, Activity, Usage, and Notifications\n * This is the primary method products should use\n */\n public async track(options: TrackOptions): Promise<TrackResult> {\n const startTime = Date.now();\n const result: TrackResult = {\n success: false,\n permissionGranted: false,\n duration: 0,\n };\n\n try {\n // Validate required fields\n this.validateOptions(options);\n\n // Step 1: Check RBAC permission (if enabled)\n if (options.rbac?.enabled !== false) {\n await this.checkPermission(options, result);\n if (!result.permissionGranted) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n } else {\n result.permissionGranted = true;\n }\n\n // Steps 2 and 3: check quota, then record usage (only for a named workspace quota)\n const usage = this.resolveUsage(options);\n if (usage) {\n let quotaAssignmentId: string | undefined;\n if (usage.checkQuota) {\n quotaAssignmentId = await this.checkQuota(options, usage, result);\n if (result.quotaAvailable === false) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n }\n await this.trackUsage(options, usage, quotaAssignmentId, result);\n }\n\n // Step 4: Log successful activity (if enabled)\n if (options.activity?.enabled !== false) {\n await this.logSuccessActivity(options, result, startTime);\n }\n\n // Step 5: Send success notification (if configured)\n if (options.notification?.onSuccess) {\n await this.sendSuccessNotification(options, result);\n }\n\n result.success = true;\n result.duration = Date.now() - startTime;\n\n logger.info('[Tracker] Operation tracked successfully', {\n action: options.action,\n duration: result.duration,\n });\n\n return result;\n } catch (error) {\n result.duration = Date.now() - startTime;\n result.success = false;\n\n // Categorize error\n if (error instanceof PermissionDeniedError) {\n result.error = {\n type: 'permission',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof QuotaExceededError) {\n result.error = {\n type: 'quota',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof ValidationError) {\n result.error = {\n type: 'validation',\n message: error.message,\n details: error.details,\n };\n } else {\n result.error = {\n type: 'unknown',\n message: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n\n // Log failed activity\n await this.logFailedActivity(options, result, startTime);\n\n // Send failure notification (if configured)\n if (options.notification?.onFailure) {\n await this.sendFailureNotification(options, result);\n }\n\n logger.error('[Tracker] Operation tracking failed', {\n action: options.action,\n error: result.error,\n duration: result.duration,\n });\n\n return result;\n }\n }\n\n /**\n * Track operation and throw on failure\n * Convenience method that throws errors instead of returning them in result\n */\n public async trackOrThrow(options: TrackOptions): Promise<TrackResult> {\n const result = await this.track(options);\n\n if (!result.success && result.error) {\n const errorMessage = result.error.message;\n const errorDetails = result.error.details;\n\n switch (result.error.type) {\n case 'permission':\n throw new PermissionDeniedError(errorMessage, errorDetails);\n case 'quota':\n throw new QuotaExceededError(errorMessage, errorDetails);\n case 'validation':\n throw new ValidationError(errorMessage, errorDetails);\n default:\n throw new Error(errorMessage);\n }\n }\n\n return result;\n }\n\n /**\n * Simplified track method for common operations.\n * The trailing metric type is accepted for source compatibility and is not metered.\n */\n public async trackSimple(\n userId: string,\n action: string,\n resourceType: string,\n resourceId?: string,\n _metricType?: UsageMetricType\n ): Promise<boolean> {\n // A metric type has no workspace quota on the owner, so trackSimple never meters usage.\n // Call track() with `usage.quotaName` to charge a quota.\n const result = await this.track({\n userId,\n action,\n resourceType,\n resourceId,\n workspaceId: this.context.workspaceId,\n usage: { enabled: false },\n });\n\n return result.success;\n }\n\n /**\n * Validate tracking options\n */\n private validateOptions(options: TrackOptions): void {\n if (!options.userId) {\n throw new ValidationError('User ID is required');\n }\n\n if (!options.action) {\n throw new ValidationError('Action is required');\n }\n\n if (!options.resourceType) {\n throw new ValidationError('Resource type is required');\n }\n }\n\n /**\n * Check RBAC permission\n */\n private async checkPermission(options: TrackOptions, result: TrackResult): Promise<void> {\n const permissionOptions: CheckPermissionOptions = {\n userId: options.userId,\n action: options.rbac?.permissionAction || options.action,\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n workspaceId: options.workspaceId,\n };\n\n const hasPermission = await this.rbac.checkPermission(permissionOptions);\n result.permissionGranted = hasPermission;\n\n if (!hasPermission) {\n result.error = {\n type: 'permission',\n message: 'Permission denied',\n details: permissionOptions as unknown as Record<string, unknown>,\n };\n }\n }\n\n /**\n * Resolve the usage step for an operation, or null when nothing is metered: usage is\n * disabled, or no workspace quota is named (a legacy `metricType` alone has no owner\n * quota to charge).\n */\n private resolveUsage(options: TrackOptions): ResolvedUsage | null {\n const usage = options.usage;\n if (!usage || usage.enabled === false) {\n return null;\n }\n const quotaName = usage.quotaName?.trim();\n if (!quotaName) {\n if (usage.metricType) {\n logger.debug('[Tracker] Usage step skipped: no quotaName for legacy metricType', {\n action: options.action,\n metricType: usage.metricType,\n });\n }\n return null;\n }\n const amount = usage.amount ?? 1;\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount === 0) {\n throw new ValidationError('Usage amount must be a finite, non-zero number');\n }\n const workspaceId = options.workspaceId ?? this.context.workspaceId;\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required to track workspace quota usage');\n }\n return {\n quotaName,\n amount,\n workspaceId,\n // Only consumption is gated; a release (negative amount) must always go through.\n checkQuota: usage.checkQuota !== false && amount > 0,\n };\n }\n\n /**\n * Check workspace quota capacity. Returns the assignment to charge when one exists.\n */\n private async checkQuota(\n options: TrackOptions,\n usage: ResolvedUsage,\n result: TrackResult\n ): Promise<string | undefined> {\n const quotaCheck = await this.usage.checkWorkspaceQuota({\n quotaName: usage.quotaName,\n amount: usage.amount,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n });\n\n result.quotaAvailable = quotaCheck.allowed;\n result.quotaRemaining = quotaCheck.limitLeft ?? undefined;\n\n if (!quotaCheck.allowed) {\n const notProvisioned = quotaCheck.assignmentId === null;\n result.error = {\n type: 'quota',\n message: notProvisioned\n ? `Quota ${usage.quotaName} is not included in this workspace's plan`\n : 'Quota exceeded',\n details: {\n quotaName: usage.quotaName,\n requestedAmount: usage.amount,\n limitLeft: quotaCheck.limitLeft,\n notProvisioned,\n },\n };\n }\n\n return quotaCheck.assignmentId ?? undefined;\n }\n\n /**\n * Record workspace quota usage with the owner.\n */\n private async trackUsage(\n options: TrackOptions,\n usage: ResolvedUsage,\n quotaAssignmentId: string | undefined,\n result: TrackResult\n ): Promise<void> {\n result.usageTracked = await this.usage.trackUsage({\n quotaName: usage.quotaName,\n productId: options.usage?.productId,\n amount: usage.amount,\n description: options.usage?.description?.trim() || `${options.action} ${options.resourceType}`,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n quotaAssignmentId,\n metadata: {\n action: options.action,\n resourceType: options.resourceType,\n ...(options.resourceId ? { resourceId: options.resourceId } : {}),\n },\n });\n }\n\n /**\n * Log successful activity\n */\n private async logSuccessActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.SUCCESS,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: options.activity?.severity || ActivitySeverity.LOW,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n }\n\n /**\n * Log failed activity\n */\n private async logFailedActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n if (options.activity?.enabled === false) {\n return;\n }\n\n try {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.FAILURE,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: ActivitySeverity.HIGH,\n errorMessage: result.error?.message,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n } catch (error) {\n logger.error('[Tracker] Failed to log activity', { error });\n }\n }\n\n /**\n * Send success notification\n */\n private async sendSuccessNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onSuccess) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onSuccess.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onSuccess.title,\n message: options.notification.onSuccess.message,\n type: options.notification.onSuccess.type || NotificationType.SUCCESS,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send success notification', { error });\n }\n }\n\n /**\n * Send failure notification\n */\n private async sendFailureNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onFailure) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onFailure.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onFailure.title,\n message: options.notification.onFailure.message,\n type: options.notification.onFailure.type || NotificationType.ERROR,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send failure notification', { error });\n }\n }\n\n /**\n * Infer activity type from action\n */\n private inferActivityType(action: string): ActivityType {\n const actionLower = action.toLowerCase();\n\n if (actionLower.includes('create') || actionLower.includes('add')) return ActivityType.CREATE;\n if (actionLower.includes('update') || actionLower.includes('edit')) return ActivityType.UPDATE;\n if (actionLower.includes('delete') || actionLower.includes('remove')) return ActivityType.DELETE;\n if (actionLower.includes('read') || actionLower.includes('view')) return ActivityType.READ;\n if (actionLower.includes('login')) return ActivityType.LOGIN;\n if (actionLower.includes('logout')) return ActivityType.LOGOUT;\n if (actionLower.includes('export')) return ActivityType.EXPORT;\n if (actionLower.includes('import')) return ActivityType.IMPORT;\n if (actionLower.includes('share')) return ActivityType.SHARE;\n if (actionLower.includes('download')) return ActivityType.DOWNLOAD;\n if (actionLower.includes('upload')) return ActivityType.UPLOAD;\n\n return ActivityType.CUSTOM;\n }\n\n /**\n * Batch track multiple operations\n */\n public async trackBatch(operations: TrackOptions[]): Promise<TrackResult[]> {\n logger.debug('[Tracker] Batch tracking operations', { count: operations.length });\n\n const results = await Promise.all(operations.map((op) => this.track(op)));\n\n logger.info('[Tracker] Batch tracking completed', {\n total: results.length,\n successful: results.filter((r) => r.success).length,\n failed: results.filter((r) => !r.success).length,\n });\n\n return results;\n }\n}\n\n// Export stub implementation for services that don't need full tracking\nexport {\n trackOperation,\n createProductTracker,\n UnifiedTrackerStub,\n trackerStub,\n UNIFIED_TRACKER_CONSTANTS,\n} from './stub.js';\nexport { isTrackedActorType, resolveAssistantSession } from './stub.js';\n// Assistant-session attribution on activity rows (BOFF-9649)\nexport { AI_ASSISTANT_ACTOR_ORIGIN } from '../activity/assistant-session.js';\nexport type { ActorOrigin, AssistantSessionAttribution } from '../activity/assistant-session.js';\nexport type {\n TrackingEvent,\n RbacCheckOptions,\n UsageTrackingOptions,\n ActivityTrackingOptions,\n UnifiedTrackingOptions,\n ProductTracker,\n TrackedActorType,\n} from './stub.js';\n\n// AI-agent activity actions and recorder (BOFF-9684)\nexport { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, trackAgentActivity } from './agent-activity.js';\nexport type { AgentActivityAction, AgentActivityOptions } from './agent-activity.js';\n\n// Opt a resolver out of the mutation-audit backstop row (see server/mutation-audit.ts)\nexport { suppressMutationAudit } from '../activity/explicit-activity-scope.js';\n\n// Re-export UsageMetricType from usage module for convenience\nexport { UsageMetricType } from '../usage/index.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,yBAAyB,OAAO,OAAO;;CAElD,eAAe;;CAEf,YAAY;;CAEZ,aAAa;;CAEb,iBAAiB;;CAEjB,gBAAgB;AAClB,CAAU;;AAKV,MAAa,+BAA+B;AAE5C,MAAM,kCAAoD,IAAI,IAAyB,CACrF,uBAAuB,YACvB,uBAAuB,cACzB,CAAC;;;;;;;;AA+BD,SAAgB,mBAAmB,SAAiD;CAClF,MAAM,UAAU,QAAQ,WAAW,CAAC,gBAAgB,IAAI,QAAQ,MAAM;CACtE,OAAO,2BAA2B,4BAA4B,SAC5D,eAAe;EACb,eAAe,QAAQ;EACvB,QAAQ,QAAQ;EAChB,WAAW;EACX,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;EAC/D,aAAa,QAAQ;EACrB,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC5D;EACA,GAAI,QAAQ,eAAe,EAAE,cAAc,QAAQ,aAAa,IAAI,CAAC;EACrE,iBAAiB;GACf,SAAS;GACT,cAAc,QAAQ;GACtB,aAAa,QAAQ,eAAe,SAAS,QAAQ,QAAQ,IAAI,QAAQ;GACzE,aAAa,QAAQ;GACrB,cAAc,QAAQ;GACtB,YAAY,QAAQ,cAAc,QAAQ;GAC1C,UAAU;IAAE,GAAG,QAAQ;IAAU,SAAS,QAAQ;GAAQ;GAC1D,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC9D;CACF,CAAC,CACH;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACsEA,IAAa,gBAAb,MAA2B;CAQf;CAPV,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YACE,QACA,AA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() {
|
|
|
250
250
|
* per-workspace loop inside a sweep. Pass `actorType: 'service'` (and the service as `actorId`)
|
|
251
251
|
* when no user is behind the work, so audit columns say who acted.
|
|
252
252
|
*
|
|
253
|
+
* Whatever `fn` returns is awaited inside the scope (see {@link runAwaitedInScope}), so a lazy
|
|
254
|
+
* thenable such as a Prisma query returned un-awaited from a plain arrow function still runs bound
|
|
255
|
+
* to the workspace.
|
|
256
|
+
*
|
|
253
257
|
* @param context - The workspace context
|
|
254
258
|
* @param fn - The function to run
|
|
255
259
|
* @returns The result of the function
|
|
@@ -258,15 +262,37 @@ function requireWorkspaceContext() {
|
|
|
258
262
|
* ```typescript
|
|
259
263
|
* await withWorkspaceContext(
|
|
260
264
|
* { workspaceId: event.workspaceId, actorId: 'wspace-tags-svc', actorType: 'service' },
|
|
261
|
-
* async () =>
|
|
265
|
+
* async () => {
|
|
266
|
+
* const result = await prisma.tag.updateMany({ where: { name }, data: { archived: true } });
|
|
267
|
+
* return result;
|
|
268
|
+
* }
|
|
262
269
|
* );
|
|
263
270
|
* ```
|
|
264
271
|
*/
|
|
265
272
|
async function withWorkspaceContext(context, fn) {
|
|
266
|
-
return
|
|
273
|
+
return runAwaitedInScope(context, fn);
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Run `fn` bound to `context` and await its result before leaving the scope (BOFF-17566).
|
|
277
|
+
*
|
|
278
|
+
* A Prisma query is a lazy thenable: it starts only when something calls its `then`. Passing
|
|
279
|
+
* `store.run(context, fn)` straight back to the caller let a callback such as
|
|
280
|
+
* `() => prisma.log.deleteMany(...)` return the un-started query, which the caller then awaited
|
|
281
|
+
* after the scope had ended, so the query ran with no workspace bound (and, under FORCE ROW LEVEL
|
|
282
|
+
* SECURITY, silently matched nothing). Awaiting inside the scope starts the query while the
|
|
283
|
+
* context is still bound. Native promises and async callbacks behave exactly as before.
|
|
284
|
+
*/
|
|
285
|
+
async function runAwaitedInScope(context, fn) {
|
|
286
|
+
return workspaceContextStore.run(context, async () => {
|
|
287
|
+
return await fn();
|
|
288
|
+
});
|
|
267
289
|
}
|
|
268
290
|
/**
|
|
269
291
|
* Run a synchronous function with a specific workspace context.
|
|
292
|
+
*
|
|
293
|
+
* The result is returned as is, so a lazy thenable (a Prisma query) returned from `fn` is not
|
|
294
|
+
* started inside the scope. Use {@link withWorkspaceContext} for anything that queries the
|
|
295
|
+
* database; this form is for synchronous work only.
|
|
270
296
|
*/
|
|
271
297
|
function withWorkspaceContextSync(context, fn) {
|
|
272
298
|
return workspaceContextStore.run(context, fn);
|
|
@@ -286,17 +312,24 @@ function withWorkspaceContextSync(context, fn) {
|
|
|
286
312
|
* @param reason - Short, static description of the work, e.g. `'retention-sweep'`. Required.
|
|
287
313
|
* @param fn - The function to run
|
|
288
314
|
*
|
|
315
|
+
* As with {@link withWorkspaceContext}, whatever `fn` returns is awaited inside the scope, so a
|
|
316
|
+
* lazy Prisma query returned un-awaited still runs in the system scope.
|
|
317
|
+
*
|
|
289
318
|
* @example
|
|
290
319
|
* ```typescript
|
|
291
|
-
* await withSystemScope('expired-session-sweep', () =>
|
|
292
|
-
* prisma.session.deleteMany({ where: { expiresAt: { lt: new Date() } } })
|
|
293
|
-
*
|
|
320
|
+
* await withSystemScope('expired-session-sweep', async () => {
|
|
321
|
+
* const result = await prisma.session.deleteMany({ where: { expiresAt: { lt: new Date() } } });
|
|
322
|
+
* return result;
|
|
323
|
+
* });
|
|
294
324
|
* ```
|
|
295
325
|
*/
|
|
296
326
|
async function withSystemScope(reason, fn) {
|
|
297
|
-
return
|
|
327
|
+
return runAwaitedInScope(createSystemScopeContext(reason), fn);
|
|
298
328
|
}
|
|
299
|
-
/**
|
|
329
|
+
/**
|
|
330
|
+
* Synchronous form of {@link withSystemScope}. Like {@link withWorkspaceContextSync}, it returns
|
|
331
|
+
* the result as is and does not start a lazy thenable inside the scope.
|
|
332
|
+
*/
|
|
300
333
|
function withSystemScopeSync(reason, fn) {
|
|
301
334
|
return workspaceContextStore.run(createSystemScopeContext(reason), fn);
|
|
302
335
|
}
|
|
@@ -1186,4 +1219,4 @@ function addWorkspaceExtension(baseClient, config) {
|
|
|
1186
1219
|
}
|
|
1187
1220
|
|
|
1188
1221
|
export { withSystemScopeSync as C, withSystemScope as S, withWorkspaceContextSync as T, resetCallerTransactionStateForTests as _, defaultWorkspaceExtensionConfig as a, runOperationWithRlsGuc as b, getScopedWorkspaceContext as c, injectCreateFields as d, injectWhereWorkspaceId as f, requireWorkspaceContext as g, maybeTagConnection as h, configureWorkspaceContextFallback as i, getWorkspaceContext as l, maybeSetRlsGuc as m, addWorkspaceExtension as n, explicitWorkspaceIdFromArgs as o, isSystemScope as p, buildTransactionContextStatement as r, getCallerTransaction as s, WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE as t, getWorkspaceContextFallbackMode as u, resetWorkspaceContextStateForTests as v, withWorkspaceContext as w, setWorkspaceContext as x, runOperationInCallerTransaction as y };
|
|
1189
|
-
//# sourceMappingURL=workspace-extension-
|
|
1222
|
+
//# sourceMappingURL=workspace-extension-feJYFO9e.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"workspace-extension-feJYFO9e.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 * **No bound context (fail closed):**\n * The context is read from AsyncLocalStorage only. Work that runs outside a request scope (stream\n * consumers, timers, workers, startup jobs) has no context and never inherits another request's:\n * with `strictMode` (the default) such operations throw until the work binds a scope with\n * `withWorkspaceContext()` (one workspace) or `withSystemScope(reason, fn)` (explicitly\n * cross-workspace). `contextFallback: 'warn'` is a deprecated, time-limited migration aid.\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';\nimport type { CfAccessCredentials } from '../types/index.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 * The Cloudflare Access credentials the request presented, bound by the SDK server together\n * with the rest of the request scope. Read only from the bound scope (never from the\n * deprecated warn-mode fallback) by `ContextManager.getCfAccessHeaders()`. Background work\n * bound with {@link withWorkspaceContext} or {@link withSystemScope} carries none.\n */\n cfAccess?: CfAccessCredentials;\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 * How {@link getWorkspaceContext} behaves when no context is bound to the current async scope.\n *\n * - `'deny'` (default): resolve nothing. The workspace extension then applies `strictMode`\n * (throw) or, with `strictMode: false`, runs the operation without injection.\n * - `'warn'`: temporary migration aid. Resolve the context most recently passed to\n * {@link setWorkspaceContext} (the previous behaviour) and log a warning each time it is\n * used, so the remaining unbound call sites can be found and fixed.\n * **Deprecated; removed after {@link WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE}.**\n */\nexport type WorkspaceContextFallbackMode = 'deny' | 'warn';\n\n/** Date after which the `'warn'` fallback mode is removed and `'deny'` is the only behaviour. */\nexport const WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE = '2027-01-08';\n\n/** Minimum interval between two warn-mode log lines (each line carries the count since the last). */\nconst FALLBACK_WARNING_INTERVAL_MS = 60_000;\n\n/** Upper bound on distinct system-scope reasons logged, so a computed reason cannot grow memory. */\nconst MAX_LOGGED_SYSTEM_SCOPE_REASONS = 256;\n\ninterface FallbackState {\n mode: WorkspaceContextFallbackMode;\n /** Last context passed to setWorkspaceContext. Only retained in 'warn' mode. */\n lastContext: WorkspaceContext | undefined;\n suppressedWarnings: number;\n lastWarningAt: number;\n}\n\nconst fallbackState: FallbackState = {\n mode: 'deny',\n lastContext: undefined,\n suppressedWarnings: 0,\n lastWarningAt: 0,\n};\n\n/**\n * Contexts created by {@link withSystemScope}. Membership, not a field, marks a system scope, so\n * a context built or spread from request data can never claim to be one.\n */\nconst systemScopeContexts = new WeakSet<WorkspaceContext>();\nconst systemScopeReasons = new WeakMap<WorkspaceContext, string>();\nconst loggedSystemScopeReasons = new Set<string>();\nlet systemScopeReasonCapLogged = false;\n\n/**\n * Select the fallback mode for this process. Called by {@link addWorkspaceExtension} from its\n * `contextFallback` option. `'warn'` is sticky for the life of the process: once any client asks\n * for it, a second client created later with the default cannot silently switch it back mid-flight.\n *\n * @internal\n */\nexport function configureWorkspaceContextFallback(mode: WorkspaceContextFallbackMode): void {\n if (mode !== 'deny' && mode !== 'warn') {\n throw new Error(`[WorkspaceExtension] Unknown contextFallback mode: ${String(mode)}`);\n }\n if (mode === 'warn' && fallbackState.mode !== 'warn') {\n fallbackState.mode = 'warn';\n logger.error(\n `[WorkspaceExtension] contextFallback 'warn' is enabled. Operations outside a bound workspace ` +\n `context will use the most recent request's context. This mode is deprecated and will be ` +\n `removed after ${WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE}; bind context with ` +\n `withWorkspaceContext() or withSystemScope() instead.`\n );\n }\n}\n\n/** The fallback mode currently in effect for this process. */\nexport function getWorkspaceContextFallbackMode(): WorkspaceContextFallbackMode {\n return fallbackState.mode;\n}\n\n/**\n * Reset module-level context state (fallback mode, retained context, log dedupe).\n *\n * @internal For unit tests only.\n */\nexport function resetWorkspaceContextStateForTests(): void {\n fallbackState.mode = 'deny';\n fallbackState.lastContext = undefined;\n fallbackState.suppressedWarnings = 0;\n fallbackState.lastWarningAt = 0;\n loggedSystemScopeReasons.clear();\n systemScopeReasonCapLogged = false;\n}\n\nfunction warnFallbackUse(context: WorkspaceContext): void {\n const now = Date.now();\n if (now - fallbackState.lastWarningAt < FALLBACK_WARNING_INTERVAL_MS) {\n fallbackState.suppressedWarnings += 1;\n return;\n }\n const suppressed = fallbackState.suppressedWarnings;\n fallbackState.lastWarningAt = now;\n fallbackState.suppressedWarnings = 0;\n // The stack is only captured when a line is actually logged (at most once per interval).\n const callSite = new Error().stack?.split('\\n').slice(2, 8).join('\\n');\n logger.warn(\n `[WorkspaceExtension] Workspace context resolved from the shared fallback (no context bound to ` +\n `this async scope). This will fail closed after ${WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE}.`,\n {\n fallbackWorkspaceId: context.workspaceId ?? 'NONE',\n suppressedSinceLastWarning: suppressed,\n callSite,\n }\n );\n}\n\n/**\n * Set workspace context for the current async scope.\n *\n * Uses `AsyncLocalStorage.enterWith()`, which binds the context to the CURRENT synchronous\n * execution and everything it schedules afterwards. It does not reach a caller that awaited the\n * function that called it, so request handlers should prefer {@link withWorkspaceContext}, which\n * binds a scope explicitly (the SDK server does this for GraphQL execution and REST endpoints).\n *\n * @param context - The workspace context for this request\n */\nexport function setWorkspaceContext(context: WorkspaceContext): void {\n workspaceContextStore.enterWith(context);\n // Only the deprecated warn mode keeps a module-level copy; the default retains nothing.\n fallbackState.lastContext = fallbackState.mode === 'warn' ? context : undefined;\n}\n\n/**\n * Get the workspace context bound to the current async scope.\n *\n * Fails closed: outside a bound scope (a background job, a stream consumer, a timer, or code\n * that lost its request scope) this returns `undefined`, unless the process opted into the\n * deprecated `contextFallback: 'warn'` mode.\n *\n * @returns The current workspace context, or undefined if none is bound\n */\nexport function getWorkspaceContext(): WorkspaceContext | undefined {\n const scoped = workspaceContextStore.getStore();\n if (scoped) return scoped;\n if (fallbackState.mode === 'warn' && fallbackState.lastContext) {\n warnFallbackUse(fallbackState.lastContext);\n return fallbackState.lastContext;\n }\n return undefined;\n}\n\n/**\n * The workspace context bound to the CURRENT async scope only. Never consults the deprecated\n * warn-mode fallback, whatever the process mode.\n *\n * Use it for values that must never leak between requests (for example the assistant-session\n * attribution on activity rows).\n */\nexport function getScopedWorkspaceContext(): WorkspaceContext | undefined {\n return workspaceContextStore.getStore();\n}\n\n/**\n * Get the bound workspace context and its workspaceId, or throw.\n *\n * Use in code that must only ever run for one workspace (resolvers, consumers that already\n * wrapped themselves in {@link withWorkspaceContext}) so a missing scope fails loudly at the\n * call site instead of deep inside a query. Reads only the scope bound to the current async\n * chain: the deprecated warn-mode fallback never satisfies it.\n *\n * @throws Error when no workspace is bound to the current async scope\n */\nexport function requireWorkspaceContext(): WorkspaceContext & { workspaceId: string } {\n const context = workspaceContextStore.getStore();\n if (!context?.workspaceId || isSystemScope(context)) {\n throw new Error(\n '[WorkspaceExtension] No workspace is bound to the current async scope. ' +\n 'Wrap the work in withWorkspaceContext({ workspaceId, ... }, fn).'\n );\n }\n return context as WorkspaceContext & { workspaceId: string };\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 * This is the explicit API for background work that acts for ONE workspace: a stream consumer\n * handling an event that names its workspace, a job row that stores its workspaceId, a\n * per-workspace loop inside a sweep. Pass `actorType: 'service'` (and the service as `actorId`)\n * when no user is behind the work, so audit columns say who acted.\n *\n * Whatever `fn` returns is awaited inside the scope (see {@link runAwaitedInScope}), so a lazy\n * thenable such as a Prisma query returned un-awaited from a plain arrow function still runs bound\n * to the workspace.\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 * await withWorkspaceContext(\n * { workspaceId: event.workspaceId, actorId: 'wspace-tags-svc', actorType: 'service' },\n * async () => {\n * const result = await prisma.tag.updateMany({ where: { name }, data: { archived: true } });\n * return result;\n * }\n * );\n * ```\n */\nexport async function withWorkspaceContext<T>(context: WorkspaceContext, fn: () => Promise<T>): Promise<T> {\n return runAwaitedInScope(context, fn);\n}\n\n/**\n * Run `fn` bound to `context` and await its result before leaving the scope (BOFF-17566).\n *\n * A Prisma query is a lazy thenable: it starts only when something calls its `then`. Passing\n * `store.run(context, fn)` straight back to the caller let a callback such as\n * `() => prisma.log.deleteMany(...)` return the un-started query, which the caller then awaited\n * after the scope had ended, so the query ran with no workspace bound (and, under FORCE ROW LEVEL\n * SECURITY, silently matched nothing). Awaiting inside the scope starts the query while the\n * context is still bound. Native promises and async callbacks behave exactly as before.\n */\nasync function runAwaitedInScope<T>(context: WorkspaceContext, fn: () => Promise<T>): Promise<T> {\n return workspaceContextStore.run(context, async () => {\n const result = await fn();\n return result;\n });\n}\n\n/**\n * Run a synchronous function with a specific workspace context.\n *\n * The result is returned as is, so a lazy thenable (a Prisma query) returned from `fn` is not\n * started inside the scope. Use {@link withWorkspaceContext} for anything that queries the\n * database; this form is for synchronous work only.\n */\nexport function withWorkspaceContextSync<T>(context: WorkspaceContext, fn: () => T): T {\n return workspaceContextStore.run(context, fn);\n}\n\n/**\n * Run a function in an explicit, audited system scope that is not tied to any workspace.\n *\n * Inside the scope the workspace extension injects nothing and does not apply `strictMode`:\n * reads see every workspace's rows and writes must set `workspaceId` themselves. Use it only for\n * genuinely cross-workspace work (retention sweeps, outbox relays, startup backfills), never to\n * silence a missing request context. Prefer one {@link withWorkspaceContext} per workspace when\n * the work can be split that way.\n *\n * Each distinct reason is logged once per process so the system scopes in use stay visible.\n * A {@link withWorkspaceContext} nested inside the scope rebinds to that workspace.\n *\n * @param reason - Short, static description of the work, e.g. `'retention-sweep'`. Required.\n * @param fn - The function to run\n *\n * As with {@link withWorkspaceContext}, whatever `fn` returns is awaited inside the scope, so a\n * lazy Prisma query returned un-awaited still runs in the system scope.\n *\n * @example\n * ```typescript\n * await withSystemScope('expired-session-sweep', async () => {\n * const result = await prisma.session.deleteMany({ where: { expiresAt: { lt: new Date() } } });\n * return result;\n * });\n * ```\n */\nexport async function withSystemScope<T>(reason: string, fn: () => Promise<T>): Promise<T> {\n return runAwaitedInScope(createSystemScopeContext(reason), fn);\n}\n\n/**\n * Synchronous form of {@link withSystemScope}. Like {@link withWorkspaceContextSync}, it returns\n * the result as is and does not start a lazy thenable inside the scope.\n */\nexport function withSystemScopeSync<T>(reason: string, fn: () => T): T {\n return workspaceContextStore.run(createSystemScopeContext(reason), fn);\n}\n\n/** Whether the given (or current) context is a system scope created by {@link withSystemScope}. */\nexport function isSystemScope(context: WorkspaceContext | undefined = workspaceContextStore.getStore()): boolean {\n return context !== undefined && systemScopeContexts.has(context);\n}\n\nfunction createSystemScopeContext(reason: string): WorkspaceContext {\n const trimmed = typeof reason === 'string' ? reason.trim() : '';\n if (!trimmed) {\n throw new Error('[WorkspaceExtension] withSystemScope requires a non-empty reason.');\n }\n const context: WorkspaceContext = Object.freeze({ actorType: 'service' });\n systemScopeContexts.add(context);\n systemScopeReasons.set(context, trimmed);\n return context;\n}\n\n/** Log the first operation run under each distinct system-scope reason. */\nfunction noteSystemScopeOperation(context: WorkspaceContext, model: string, operation: string): void {\n const reason = systemScopeReasons.get(context) ?? 'unknown';\n if (loggedSystemScopeReasons.has(reason)) return;\n if (loggedSystemScopeReasons.size >= MAX_LOGGED_SYSTEM_SCOPE_REASONS) {\n if (!systemScopeReasonCapLogged) {\n systemScopeReasonCapLogged = true;\n logger.warn(\n `[WorkspaceExtension] More than ${MAX_LOGGED_SYSTEM_SCOPE_REASONS} distinct system-scope reasons; ` +\n 'further new reasons are not logged. Reasons should be short static strings.',\n { reason, model, operation }\n );\n }\n return;\n }\n loggedSystemScopeReasons.add(reason);\n logger.info('[WorkspaceExtension] Operation running in an explicit system scope (no workspace injection)', {\n reason,\n model,\n operation,\n });\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 * What happens when an operation runs with no workspace context bound to its async scope.\n *\n * - `'deny'` (default): nothing is resolved, so `strictMode` throws (or, with\n * `strictMode: false`, the operation runs without injection). Background work must bind its\n * scope with `withWorkspaceContext()` or `withSystemScope()`.\n * - `'warn'`: deprecated migration aid. Reuse the context of the most recent request and log a\n * warning. Removed after {@link WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE}. Once any client in\n * the process selects it, it stays on for that process.\n *\n * @default 'deny'\n */\n contextFallback?: WorkspaceContextFallbackMode;\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 contextFallback: 'deny',\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// Operation Context Resolution\n// ============================================================================\n\n/**\n * Contexts synthesized from an operation's own arguments. They satisfy strict mode and\n * scope injection, but never set the RLS / connection tags: row-level security keeps\n * whatever the connection or caller transaction already carries, so it stays an\n * independent check on the explicit workspaceId instead of following it.\n */\nconst explicitArgumentContexts = new WeakSet<WorkspaceContext>();\n\n/** Read a non-empty string `workspaceId` set directly on a where/data object. */\nfunction readExplicitWorkspaceId(value: unknown): string | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n const workspaceId = (value as Record<string, unknown>)['workspaceId'];\n return typeof workspaceId === 'string' && workspaceId.length > 0 ? workspaceId : undefined;\n}\n\n/**\n * The single workspace an operation's own arguments pin it to, if any.\n *\n * Only a plain string `workspaceId` at the top level of `where` (reads, updates, deletes) or\n * `data` (creates) counts. Filters such as `{ in: [...] }`, relation paths and compound unique\n * keys do not, and a `createMany` whose rows name different workspaces does not either: those\n * stay unresolved so strict mode still applies.\n *\n * @internal Exported for unit tests.\n */\nexport function explicitWorkspaceIdFromArgs(operation: string, args: Record<string, unknown>): string | undefined {\n switch (operation) {\n case 'create':\n return readExplicitWorkspaceId(args['data']);\n case 'createMany':\n case 'createManyAndReturn': {\n const data = args['data'];\n const rows = Array.isArray(data) ? data : [data];\n if (rows.length === 0) return undefined;\n const ids = rows.map(readExplicitWorkspaceId);\n const first = ids[0];\n return first !== undefined && ids.every((id) => id === first) ? first : undefined;\n }\n case 'upsert': {\n const fromWhere = readExplicitWorkspaceId(args['where']);\n if (!fromWhere) return undefined;\n const fromCreate = readExplicitWorkspaceId(args['create']);\n if (args['create'] && typeof args['create'] === 'object' && 'workspaceId' in args['create']) {\n return fromCreate === fromWhere ? fromWhere : undefined;\n }\n return fromWhere;\n }\n default:\n return readExplicitWorkspaceId(args['where']);\n }\n}\n\n/**\n * Resolve the workspace context for one model operation.\n *\n * 1. A context bound to the async scope always wins (request scopes, withWorkspaceContext,\n * withSystemScope). A bound request scope with no workspace stays without one, so strict\n * mode keeps rejecting workspace-less requests exactly as before.\n * 2. With NO scope bound (background work), an operation whose own arguments pin one\n * workspace (`where.workspaceId` / `data.workspaceId`) runs scoped to that workspace, with\n * no actor attributed. It does not set the RLS GUC or connection tag: under FORCE row-level\n * security such work still needs a bound scope. This is the explicit-argument path.\n * 3. Otherwise the deprecated warn-mode fallback, if the process opted in.\n * 4. Otherwise nothing: strict mode throws, non-strict runs without injection.\n */\nfunction resolveOperationContext(operation: string, args: Record<string, unknown>): WorkspaceContext | undefined {\n const scoped = workspaceContextStore.getStore();\n if (scoped) return scoped;\n const explicitWorkspaceId = explicitWorkspaceIdFromArgs(operation, args);\n if (explicitWorkspaceId) {\n const context: WorkspaceContext = { workspaceId: explicitWorkspaceId };\n explicitArgumentContexts.add(context);\n return context;\n }\n return getWorkspaceContext();\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 // An explicit system scope (withSystemScope) is the audited opt-out for cross-workspace work.\n if (isSystemScope(wsCtx)) {\n noteSystemScopeOperation(wsCtx as WorkspaceContext, model, operation);\n return;\n }\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 is bound to the current async scope` +\n (wsCtx ? '' : ' (background work must bind one explicitly)') +\n `. Either: ` +\n `(1) run the work inside withWorkspaceContext({ workspaceId, ... }, fn), ` +\n `(2) run genuinely cross-workspace work inside withSystemScope(reason, fn), ` +\n `(3) add \"${model}\" to excludeModels or \"${opKey}\" to allowedUnguardedOperations, or ` +\n `(4) 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 configureWorkspaceContextFallback(fullConfig.contextFallback);\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). An explicit-argument\n // context never tags either, so RLS stays independent of the arguments.\n if (!tagsTransactions || explicitArgumentContexts.has(wsCtx)) 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 contextFallback: getWorkspaceContextFallbackMode(),\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 = resolveOperationContext('create', args);\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 = resolveOperationContext('createMany', args);\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 = resolveOperationContext('createManyAndReturn', args);\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 = resolveOperationContext('update', args);\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 = resolveOperationContext('updateMany', args);\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 = resolveOperationContext('upsert', args);\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 = resolveOperationContext('findMany', args);\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 = resolveOperationContext('findFirst', args);\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 = resolveOperationContext('findFirstOrThrow', args);\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 = resolveOperationContext('findUnique', args);\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 = resolveOperationContext('findUniqueOrThrow', args);\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 = resolveOperationContext('count', args);\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 = resolveOperationContext('aggregate', args);\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 = resolveOperationContext('groupBy', args);\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 = resolveOperationContext('delete', args);\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 = resolveOperationContext('deleteMany', args);\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,MAAM,gBAAgB,oBAAoB;EAC1C,MAAM,WAAW,gBAAgB,EAAE,GAAG,cAAc,IAAI;EACxD,MAAM,UAAU,kBAAkB,SAAS;EAC3C,OAAO,IAAI,MAAM,OAAO,EACtB,IAAI,QAAQ,UAAU,UAAU;GAC9B,MAAM,WAAW,QAAQ,IAAI,QAAQ,UAAU,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IAAI,MAAM,gFAAgF;EAElG,IAAI,MAAM,QAAQ,KAAK,GAAG;GACxB,MAAM,QAAQ,oBAAoB;GAClC,MAAM,YACJ,oBAAoB,OAAO,cAAc,iCAAiC,OAAO,UAAU,IAAI;GACjG,IAAI,WAAW;IACb,MAAM,aAAa,+BAA+B,kBAAkB,UAAU,KAAK,GAAG,UAAU,MAAM;IACtG,OAAO,OACJ,aAAa,CAAC,YAAY,GAAG,KAAK,GAAG,OAAO,CAAC,CAC7C,MAAM,YAAa,MAAM,QAAQ,OAAO,IAAI,QAAQ,MAAM,CAAC,IAAI,OAAQ;GAC5E;EACF;EAGA,IAAI,OAAO,UAAU,YAAY;GAG/B,MAAM,WAAW;GACjB,OAAO,oBAAoB,KACzB,MACA,OAAO,OAAe;IACpB,MAAM,QAAQ,EAAE,QAAQ,KAAK;IAC7B,IAAI;KACF,OAAO,MAAM,SAAS,uBAAuB,IAAI,OAAO,mBAAmB,CAAC;IAC9E,UAAU;KACR,MAAM,SAAS;IACjB;GACF,GACA,OACF;EACF;EACA,OAAO,oBAAoB,KAAK,MAAM,OAAO,OAAO;CACtD,EACF,EACF,CAAC;AACH"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@burdenoff/be-sdk",
|
|
3
|
-
"version": "2026.
|
|
3
|
+
"version": "2026.1201.2",
|
|
4
4
|
"description": "Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"bun-runtime-metrics-CPy5D6NT.js","names":[],"sources":["../src/telemetry/bun-runtime-metrics.ts"],"sourcesContent":["/**\n * Runtime metrics that stall a Bun process (BOFF-12287).\n *\n * `v8.getHeapStatistics()` and `v8.getHeapSpaceStatistics()` are cheap under\n * Node. Under Bun 1.4 they walk the whole JavaScriptCore heap synchronously:\n * about 0.44 s per call on a 3M-object heap, during which the process serves\n * nothing. Two collectors that be-sdk services load call one of them on a\n * timer, so every Bun 1.4 service paid a recurring block sized to its heap:\n *\n * - prom-client's default `nodejs_heap_space_size_*_bytes` gauges, on every\n * Prometheus scrape. Bun 1.3 threw `ERR_NOT_IMPLEMENTED` and prom-client\n * skipped them; Bun 1.4 implements the call, so from the Bun 1.4.4 upgrade\n * on the scrape itself became the block (wspace-int-gateway: 0.01 s →\n * 0.5–0.76 s per scrape). Handled here.\n * - the OpenTelemetry `runtime-node` instrumentation, on every 60 s OTLP\n * metric export. Handled in `sdk.ts` (`autoInstrumentationConfig`).\n *\n * Heap size stays visible through prom-client's `nodejs_heap_size_*_bytes`,\n * which reads `process.memoryUsage()`, and event-loop lag through\n * `nodejs_eventloop_lag_*`. No dashboard or alert reads the dropped series.\n */\n\n/** True when the process runs on Bun (also inside a `bun build --compile` binary). */\nexport function isBunRuntime(): boolean {\n return typeof process.versions['bun'] === 'string';\n}\n\n/**\n * prom-client default metrics that are not served under Bun. The `total` gauge\n * carries the collect callback that calls `v8.getHeapSpaceStatistics()`; the\n * other two are only filled by it, so all three go.\n */\nexport const BUN_HEAP_WALK_DEFAULT_METRICS: readonly string[] = [\n 'nodejs_heap_space_size_total_bytes',\n 'nodejs_heap_space_size_used_bytes',\n 'nodejs_heap_space_size_available_bytes',\n];\n\n/** The part of the `prom-client` module that {@link collectPromDefaultMetrics} uses. */\nexport interface PromDefaultMetricsClient {\n register: { removeSingleMetric: (name: string) => void };\n collectDefaultMetrics: (opts?: Record<string, unknown>) => void;\n}\n\n/**\n * Registers prom-client's default metrics on `prom.register` and, under Bun,\n * removes the heap-space gauges again.\n *\n * Safe to call on every scrape: prom-client throws on the first metric name\n * that is already registered, before it reaches the heap-space gauges, and the\n * removal is a map delete. Calling it again also removes the gauges when the\n * service registered the default metrics on the same registry itself.\n *\n * prom-client probes `v8.getHeapSpaceStatistics()` once when it registers the\n * defaults, so a Bun process still pays one heap walk, on its first scrape.\n */\nexport function collectPromDefaultMetrics(prom: PromDefaultMetricsClient, bun: boolean = isBunRuntime()): void {\n try {\n prom.collectDefaultMetrics({ register: prom.register });\n } catch {\n // Already registered on this registry: prom-client rejects duplicate names.\n }\n if (!bun) return;\n for (const name of BUN_HEAP_WALK_DEFAULT_METRICS) prom.register.removeSingleMetric(name);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eAAwB;CACtC,OAAO,OAAO,QAAQ,SAAS,WAAW;AAC5C;;;;;;AAOA,MAAa,gCAAmD;CAC9D;CACA;CACA;AACF;;;;;;;;;;;;;AAoBA,SAAgB,0BAA0B,MAAgC,MAAe,aAAa,GAAS;CAC7G,IAAI;EACF,KAAK,sBAAsB,EAAE,UAAU,KAAK,SAAS,CAAC;CACxD,QAAQ,CAER;CACA,IAAI,CAAC,KAAK;CACV,KAAK,MAAM,QAAQ,+BAA+B,KAAK,SAAS,mBAAmB,IAAI;AACzF"}
|