@burdenoff/be-sdk 2026.1128.2 → 2026.1128.3

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.
@@ -1,4 +1,4 @@
1
- import { c as getScopedWorkspaceContext } from "../workspace-extension-ByopOwtK.js";
1
+ import { c as getScopedWorkspaceContext } from "../workspace-extension-BcMPoGWr.js";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
 
4
4
  // src/context/index.ts
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import { c as tenant_notifications_exports, r as NotificationsModule, s as Tenan
9
9
  import { c as createRBACDirectiveFromEnv, o as createRBACDirective, s as createRBACDirectiveForLayer, t as RBACModule } from "./rbac-pRCcWVS_.js";
10
10
  import { ActivityModule, ActivityOperationUnsupportedError } from "./activity/index.js";
11
11
  import { a as UsageModule, c as BillingUsageClient } from "./usage-BK7eyP42.js";
12
- import { t as TrackerModule } from "./tracker-DE4MDVTr.js";
12
+ import { t as TrackerModule } from "./tracker-CDVYIoCb.js";
13
13
  import { DatabaseModule } from "./database/index.js";
14
14
  import { T as EventsModule, t as event_queue_exports } from "./event-queue-CKvgAqF3.js";
15
15
  import { a as unregisterDisposable, i as registerDisposable, n as disposeAll, r as getRegisteredDisposableCount, t as lifecycle_exports } from "./lifecycle-DeoLSX0U.js";
@@ -31,7 +31,7 @@ import { t as cache_exports } from "./cache-CU0uLwcS.js";
31
31
  import { t as middleware_exports } from "./middleware-Cq0zFMGp.js";
32
32
  import { t as observability_exports } from "./observability-DBDXipTU.js";
33
33
  import { t as graphql_exports } from "./graphql-DHAHHcww.js";
34
- import { t as prisma_exports } from "./prisma-1J9WTyAF.js";
34
+ import { t as prisma_exports } from "./prisma-CUij0pph.js";
35
35
  import { v as utils_exports } from "./utils-DpW6K_iB.js";
36
36
  import { a as getLanguage, c as t, i as createTranslator, o as getLocale, r as i18n_exports, s as hasI18n } from "./i18n-BBMYFd0P.js";
37
37
  import { t as export_exports } from "./export-D3EySJjJ.js";
@@ -1,6 +1,6 @@
1
- import { C as withSystemScopeSync, S as withSystemScope, T as withWorkspaceContextSync, _ as resetCallerTransactionStateForTests, a as defaultWorkspaceExtensionConfig, b as runOperationWithRlsGuc, c as getScopedWorkspaceContext, d as injectCreateFields, f as injectWhereWorkspaceId, g as requireWorkspaceContext, h as maybeTagConnection, i as configureWorkspaceContextFallback, l as getWorkspaceContext, m as maybeSetRlsGuc, n as addWorkspaceExtension, o as explicitWorkspaceIdFromArgs, p as isSystemScope, r as buildTransactionContextStatement, s as getCallerTransaction, t as WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, u as getWorkspaceContextFallbackMode, v as resetWorkspaceContextStateForTests, w as withWorkspaceContext, x as setWorkspaceContext, y as runOperationInCallerTransaction } from "../workspace-extension-ByopOwtK.js";
1
+ import { C as withSystemScopeSync, S as withSystemScope, T as withWorkspaceContextSync, _ as resetCallerTransactionStateForTests, a as defaultWorkspaceExtensionConfig, b as runOperationWithRlsGuc, c as getScopedWorkspaceContext, d as injectCreateFields, f as injectWhereWorkspaceId, g as requireWorkspaceContext, h as maybeTagConnection, i as configureWorkspaceContextFallback, l as getWorkspaceContext, m as maybeSetRlsGuc, n as addWorkspaceExtension, o as explicitWorkspaceIdFromArgs, p as isSystemScope, r as buildTransactionContextStatement, s as getCallerTransaction, t as WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, u as getWorkspaceContextFallbackMode, v as resetWorkspaceContextStateForTests, w as withWorkspaceContext, x as setWorkspaceContext, y as runOperationInCallerTransaction } from "../workspace-extension-BcMPoGWr.js";
2
2
  import { a as createConnectionPool, c as ensureServiceApplicationName, d as isTransientAcquireError, f as normalizeSqlTemplate, i as configurePrismaLogging, l as fingerprintSqlQuery, o as createPrismaAdapter, r as PrismaClientWrapper, s as createPrismaClient, u as installAcquireRetry } from "../middleware-z8KzMFU_.js";
3
- import { C as isDatabaseInitialized, D as resolvePoolTuningFromEnv, E as createDatabaseClientFromEnv, S as initializeDatabaseWithConfig, T as createDatabaseClient, _ as testConnection, a as createContextFromSDK, b as getDb, c as toContextJson, d as getModelFields, f as hasModel, g as getDatabaseVersion, h as getDatabaseStats, i as contextMatches, l as extractFieldsFromModel, m as checkDatabaseHealth, n as buildContextWhereClause, o as mergeContext, p as loadGeneratedFields, r as buildContextWhereConditions, s as parseContext, u as getAllModelNames, v as getDatabaseManager, w as resetDatabaseManager, x as initializeDatabase, y as getDatabaseProductName } from "../prisma-1J9WTyAF.js";
3
+ import { C as isDatabaseInitialized, D as resolvePoolTuningFromEnv, E as createDatabaseClientFromEnv, S as initializeDatabaseWithConfig, T as createDatabaseClient, _ as testConnection, a as createContextFromSDK, b as getDb, c as toContextJson, d as getModelFields, f as hasModel, g as getDatabaseVersion, h as getDatabaseStats, i as contextMatches, l as extractFieldsFromModel, m as checkDatabaseHealth, n as buildContextWhereClause, o as mergeContext, p as loadGeneratedFields, r as buildContextWhereConditions, s as parseContext, u as getAllModelNames, v as getDatabaseManager, w as resetDatabaseManager, x as initializeDatabase, y as getDatabaseProductName } from "../prisma-CUij0pph.js";
4
4
 
5
5
  export { PrismaClientWrapper, WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, addWorkspaceExtension, buildContextWhereClause, buildContextWhereConditions, buildTransactionContextStatement, checkDatabaseHealth, configurePrismaLogging, configureWorkspaceContextFallback, contextMatches, createConnectionPool, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, createPrismaAdapter, createPrismaClient, defaultWorkspaceExtensionConfig, ensureServiceApplicationName, explicitWorkspaceIdFromArgs, extractFieldsFromModel, fingerprintSqlQuery, getAllModelNames, getCallerTransaction, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, getScopedWorkspaceContext, getWorkspaceContext, getWorkspaceContextFallbackMode, hasModel, initializeDatabase, initializeDatabaseWithConfig, injectCreateFields, injectWhereWorkspaceId, installAcquireRetry, isDatabaseInitialized, isSystemScope, isTransientAcquireError, loadGeneratedFields, maybeSetRlsGuc, maybeTagConnection, mergeContext, normalizeSqlTemplate, parseContext, requireWorkspaceContext, resetCallerTransactionStateForTests, resetDatabaseManager, resetWorkspaceContextStateForTests, resolvePoolTuningFromEnv, runOperationInCallerTransaction, runOperationWithRlsGuc, setWorkspaceContext, testConnection, toContextJson, withSystemScope, withSystemScopeSync, withWorkspaceContext, withWorkspaceContextSync };
6
6
  //# sourceMappingURL=index.js.map
@@ -2,7 +2,7 @@ import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
2
2
  import { a as logger } from "./logger-B6rCpb7D.js";
3
3
  import { a as createConnectionPool, c as ensureServiceApplicationName, d as isTransientAcquireError, f as normalizeSqlTemplate, i as configurePrismaLogging, l as fingerprintSqlQuery, o as createPrismaAdapter, r as PrismaClientWrapper, s as createPrismaClient, t as addGraphExtension, u as installAcquireRetry } from "./middleware-z8KzMFU_.js";
4
4
  import { r as getGraphEventEmitter } from "./graph-emitter-DpaWxRBp.js";
5
- import { C as withSystemScopeSync, S as withSystemScope, T as withWorkspaceContextSync, _ as resetCallerTransactionStateForTests, a as defaultWorkspaceExtensionConfig, b as runOperationWithRlsGuc, c as getScopedWorkspaceContext, d as injectCreateFields, f as injectWhereWorkspaceId, g as requireWorkspaceContext, h as maybeTagConnection, i as configureWorkspaceContextFallback, l as getWorkspaceContext, m as maybeSetRlsGuc, n as addWorkspaceExtension, o as explicitWorkspaceIdFromArgs, p as isSystemScope, r as buildTransactionContextStatement, s as getCallerTransaction, t as WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, u as getWorkspaceContextFallbackMode, v as resetWorkspaceContextStateForTests, w as withWorkspaceContext, x as setWorkspaceContext, y as runOperationInCallerTransaction } from "./workspace-extension-ByopOwtK.js";
5
+ import { C as withSystemScopeSync, S as withSystemScope, T as withWorkspaceContextSync, _ as resetCallerTransactionStateForTests, a as defaultWorkspaceExtensionConfig, b as runOperationWithRlsGuc, c as getScopedWorkspaceContext, d as injectCreateFields, f as injectWhereWorkspaceId, g as requireWorkspaceContext, h as maybeTagConnection, i as configureWorkspaceContextFallback, l as getWorkspaceContext, m as maybeSetRlsGuc, n as addWorkspaceExtension, o as explicitWorkspaceIdFromArgs, p as isSystemScope, r as buildTransactionContextStatement, s as getCallerTransaction, t as WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, u as getWorkspaceContextFallbackMode, v as resetWorkspaceContextStateForTests, w as withWorkspaceContext, x as setWorkspaceContext, y as runOperationInCallerTransaction } from "./workspace-extension-BcMPoGWr.js";
6
6
  import { D as productSlugVariants, g as isSameProductSlug } from "./product-alias-BPqtskMq.js";
7
7
  import { createRequire } from "node:module";
8
8
 
@@ -871,4 +871,4 @@ var prisma_exports = /* @__PURE__ */ __exportAll({
871
871
  });
872
872
 
873
873
  export { isDatabaseInitialized as C, resolvePoolTuningFromEnv as D, createDatabaseClientFromEnv as E, initializeDatabaseWithConfig as S, createDatabaseClient as T, testConnection as _, createContextFromSDK as a, getDb as b, toContextJson as c, getModelFields as d, hasModel as f, getDatabaseVersion as g, getDatabaseStats as h, contextMatches as i, extractFieldsFromModel as l, checkDatabaseHealth as m, buildContextWhereClause as n, mergeContext as o, loadGeneratedFields as p, buildContextWhereConditions as r, parseContext as s, prisma_exports as t, getAllModelNames as u, getDatabaseManager as v, resetDatabaseManager as w, initializeDatabase as x, getDatabaseProductName as y };
874
- //# sourceMappingURL=prisma-1J9WTyAF.js.map
874
+ //# sourceMappingURL=prisma-CUij0pph.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"prisma-1J9WTyAF.js","names":[],"sources":["../src/prisma/factory.ts","../src/prisma/manager.ts","../src/prisma/health.ts","../src/prisma/fields.ts","../src/prisma/context.ts","../src/prisma/index.ts"],"sourcesContent":["/**\n * Database Client Factory\n *\n * Provides a unified factory for creating fully-configured database clients\n * with Prisma 7, PostgreSQL adapter, graph extension, and graceful shutdown.\n *\n * This module consolidates all database setup into a single call, reducing\n * boilerplate across all backend services.\n *\n * @module prisma/factory\n * @category Database\n */\n\nimport { logger } from '../logger/index.js';\nimport {\n createPrismaClient,\n ensureServiceApplicationName,\n type PrismaClientBase,\n type PrismaClientWrapper,\n type PrismaClientConstructorOptions,\n} from './client.js';\nimport type { PrismaClientConfig } from './types.js';\nimport { addGraphExtension, type GraphMiddlewareConfig, type GraphEventEmitter } from '../graph/middleware/index.js';\nimport { getGraphEventEmitter } from '../event-queue/graph-emitter.js';\nimport { addWorkspaceExtension, type WorkspaceExtensionConfig } from './workspace-extension.js';\n\n/**\n * Configuration for creating a database client\n */\nexport interface DatabaseClientConfig extends PrismaClientConfig {\n /**\n * Product name for graph events (e.g., 'module-tags', 'workspaces')\n */\n productName: string;\n\n /**\n * Enable graph extension for entity sync\n * @default true (reads from GRAPH_MIDDLEWARE_ENABLED env var)\n */\n enableGraphExtension?: boolean;\n\n /**\n * Custom graph event emitter (defaults to NATS-based emitter)\n */\n graphEventEmitter?: GraphEventEmitter;\n\n /**\n * Enable workspace extension for automatic workspaceId injection.\n *\n * Default is layer-aware:\n * - Global-layer services (`productName` starting with `global-` or `global_`,\n * or `WORKSPACE_LAYER=global`) default to `false`. Global-layer tables\n * (Tenant, Organization, Workspace, PlatformProduct, etc.) are intentionally\n * not workspace-scoped — enforcing workspaceId on them would block legitimate\n * queries like `myOrganizations`, `myWorkspaces`, `myAccessibleProducts`.\n * - All other services (wspace layer, product backends) default to `true`.\n *\n * `WORKSPACE_EXTENSION_ENABLED` env var always wins when explicitly set\n * (`true` or `false`). Pass the field on `config` for code-level override.\n */\n enableWorkspaceExtension?: boolean;\n\n /**\n * Configuration for the workspace extension\n */\n workspaceExtensionConfig?: WorkspaceExtensionConfig;\n\n /**\n * Register process shutdown handlers for graceful shutdown\n * @default true\n */\n registerShutdownHandlers?: boolean;\n}\n\n/**\n * Result of creating a database client\n */\nexport interface DatabaseClient<T extends PrismaClientBase> {\n /**\n * The extended Prisma client for database operations\n * Use this for all queries: db.model.operation()\n */\n db: T & { client: T };\n\n /**\n * The Prisma client wrapper with connection management utilities\n */\n wrapper: PrismaClientWrapper<T>;\n\n /**\n * Connect to the database with retry logic\n */\n connect: (retries?: number, delay?: number) => Promise<void>;\n\n /**\n * Disconnect from the database\n */\n disconnect: () => Promise<void>;\n}\n\n/**\n * Layer-aware default for the workspace extension.\n *\n * Global-layer services (productName starting with `global-`/`global_`, or\n * `WORKSPACE_LAYER=global`) opt out by default because their tables don't carry\n * a workspaceId column — enforcement would break queries like `myOrganizations`,\n * `myAccessibleProducts`, `contentPages`.\n *\n * `WORKSPACE_EXTENSION_ENABLED` is respected as an explicit override.\n */\nfunction resolveWorkspaceExtensionDefault(productName: string): boolean {\n const explicit = process.env['WORKSPACE_EXTENSION_ENABLED'];\n if (explicit === 'true') return true;\n if (explicit === 'false') return false;\n\n const layer = process.env['WORKSPACE_LAYER']?.toLowerCase();\n if (layer === 'global') return false;\n if (layer === 'wspace') return true;\n\n const name = productName.toLowerCase();\n if (name.startsWith('global-') || name.startsWith('global_')) return false;\n return true;\n}\n\n/**\n * Create a fully-configured database client with graph extension\n *\n * This is the recommended way to create a database connection in all backend services.\n * It handles:\n * - Prisma client creation with PostgreSQL adapter\n * - Connection pooling configuration\n * - Query logging (in development)\n * - Graph extension for entity sync (via NATS or in-memory)\n * - Graceful shutdown handlers\n *\n * @example\n * ```typescript\n * // In your service's db.ts\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { createDatabaseClient } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, wrapper, connect, disconnect } = createDatabaseClient(PrismaClient, {\n * productName: 'my-service',\n * databaseUrl: process.env.DATABASE_URL!,\n * });\n *\n * export { db, wrapper, connect, disconnect };\n * export type ExtendedPrismaClient = typeof db;\n * ```\n *\n * @example\n * ```typescript\n * // With custom configuration\n * const { db } = createDatabaseClient(PrismaClient, {\n * productName: 'workspaces',\n * databaseUrl: process.env.DATABASE_URL!,\n * maxConnections: 50,\n * enableQueryLogging: true,\n * slowQueryThreshold: 200,\n * enableGraphExtension: true,\n * registerShutdownHandlers: true,\n * });\n * ```\n */\nexport function createDatabaseClient<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n config: DatabaseClientConfig\n): DatabaseClient<T> {\n const {\n productName,\n enableGraphExtension = process.env['GRAPH_MIDDLEWARE_ENABLED'] !== 'false',\n graphEventEmitter,\n enableWorkspaceExtension = resolveWorkspaceExtensionDefault(productName),\n workspaceExtensionConfig,\n registerShutdownHandlers = true,\n ...prismaConfig\n } = config;\n\n // Tag every service's pool with `svc=<productName>` by default so its\n // connections are attributable in pg_stat_activity / pg_stat_statements\n // (the on-ramp to per-workspace observability and shard routing). This is\n // pure diagnostic metadata with no effect on behavior; explicit\n // `applicationName` on the config always wins.\n const prismaConfigWithDefaults: PrismaClientConfig = {\n ...prismaConfig,\n applicationName: prismaConfig.applicationName ?? `svc=${productName}`,\n };\n\n // Belt-and-suspenders: also set the PGAPPNAME env fallback so any additional\n // pools this service opens outside be-sdk still carry the per-service tag.\n ensureServiceApplicationName(productName);\n\n // Create Prisma client wrapper\n const wrapper = createPrismaClient(PrismaClientConstructor, prismaConfigWithDefaults);\n\n // Get the base client\n const baseClient = wrapper.getClient();\n\n // Extension chaining order:\n // 1. Graph extension (event emission on CRUD) - runs first\n // 2. Workspace extension (auto-inject workspaceId) - runs second\n //\n // The workspace extension should run BEFORE graph extension in the\n // interception chain so that graph events include the injected workspaceId.\n // In Prisma $extends, the LAST extension added runs FIRST (outermost wrapper).\n // So we add graph first, then workspace on top.\n\n let extendedClient: T;\n\n // Step 1: Add graph extension\n if (enableGraphExtension) {\n const eventEmitter = graphEventEmitter ?? getGraphEventEmitter();\n\n const graphConfig: GraphMiddlewareConfig = {\n enabled: true,\n productName,\n eventEmitter,\n };\n\n extendedClient = addGraphExtension(baseClient, graphConfig);\n\n logger.info('[Database] Graph extension enabled', { productName });\n } else {\n extendedClient = baseClient;\n logger.info('[Database] Graph extension disabled');\n }\n\n // Step 2: Add workspace extension (wraps on top of graph)\n if (enableWorkspaceExtension) {\n extendedClient = addWorkspaceExtension(extendedClient, workspaceExtensionConfig);\n\n logger.info('[Database] Workspace extension enabled', { productName });\n } else {\n logger.info('[Database] Workspace extension disabled');\n }\n\n // Add backwards compatibility alias\n const db = extendedClient as T & { client: T };\n (db as unknown as Record<string, unknown>)['client'] = db;\n\n // Register shutdown handlers if requested\n if (registerShutdownHandlers) {\n wrapper.registerShutdownHandlers();\n logger.debug('[Database] Shutdown handlers registered');\n }\n\n return {\n db,\n wrapper,\n connect: (retries?: number, delay?: number) => wrapper.connect(retries, delay),\n disconnect: () => wrapper.disconnect(),\n };\n}\n\n/**\n * Pool-tuning options resolved from environment variables.\n */\nexport interface PoolTuningEnv {\n /** Postgres application_name (defaults to `svc=<productName>`). */\n applicationName: string;\n /** Client-side node-postgres query_timeout in ms, if opted in (pooler-safe). */\n queryTimeoutMillis?: number;\n /** Server-side statement_timeout in ms, if opted in. */\n statementTimeoutMillis?: number;\n /** Server-side idle_in_transaction_session_timeout in ms, if opted in. */\n idleInTransactionTimeoutMillis?: number;\n /** Server-side lock_timeout in ms, if opted in. */\n lockTimeoutMillis?: number;\n}\n\n/**\n * Parse a strictly-positive integer environment variable.\n *\n * Returns `undefined` for unset, empty, non-numeric, zero, or negative values —\n * so a misconfigured or absent env var can never silently enable an aggressive\n * (or nonsensical) timeout. This is what keeps the DB-enforced timeouts OFF by\n * default and therefore behavior-preserving.\n */\nfunction parsePositiveIntEnv(name: string): number | undefined {\n const raw = process.env[name];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n const parsed = Number.parseInt(raw.trim(), 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\n/**\n * Resolve pool tuning (application_name + opt-in DB timeouts) from env vars:\n * - DATABASE_APPLICATION_NAME: overrides the default `svc=<productName>` tag\n * - DATABASE_QUERY_TIMEOUT: client-side node-postgres query_timeout in ms (opt-in, pooler-safe)\n * - DATABASE_STATEMENT_TIMEOUT: server-side statement_timeout in ms (opt-in; DIRECT :5432 only — see note)\n * - DATABASE_IDLE_IN_TRANSACTION_TIMEOUT: idle_in_transaction_session_timeout in ms (opt-in)\n * - DATABASE_LOCK_TIMEOUT: lock_timeout in ms (opt-in)\n *\n * Timeouts are omitted entirely unless explicitly set to a positive integer, so\n * the default is exactly today's behavior (no timeouts).\n *\n * NOTE: prefer `DATABASE_QUERY_TIMEOUT` for services whose `DATABASE_URL` points\n * at the built-in PgBouncer (`:6432`). `DATABASE_STATEMENT_TIMEOUT` and friends\n * are Postgres startup parameters that Azure PgBouncer does not pass through, so\n * they silently have no effect (or fail the connection) on the pooled path.\n */\nexport function resolvePoolTuningFromEnv(productName: string): PoolTuningEnv {\n const tuning: PoolTuningEnv = {\n applicationName: process.env['DATABASE_APPLICATION_NAME']?.trim() || `svc=${productName}`,\n };\n\n const queryTimeout = parsePositiveIntEnv('DATABASE_QUERY_TIMEOUT');\n if (queryTimeout !== undefined) {\n tuning.queryTimeoutMillis = queryTimeout;\n }\n\n const statementTimeout = parsePositiveIntEnv('DATABASE_STATEMENT_TIMEOUT');\n if (statementTimeout !== undefined) {\n tuning.statementTimeoutMillis = statementTimeout;\n }\n\n const idleInTransactionTimeout = parsePositiveIntEnv('DATABASE_IDLE_IN_TRANSACTION_TIMEOUT');\n if (idleInTransactionTimeout !== undefined) {\n tuning.idleInTransactionTimeoutMillis = idleInTransactionTimeout;\n }\n\n const lockTimeout = parsePositiveIntEnv('DATABASE_LOCK_TIMEOUT');\n if (lockTimeout !== undefined) {\n tuning.lockTimeoutMillis = lockTimeout;\n }\n\n return tuning;\n}\n\n/**\n * Create a database client from environment variables\n *\n * Convenience function that reads configuration from standard environment variables:\n * - DATABASE_URL: Connection string (required)\n * - DATABASE_MAX_CONNECTIONS: Max pool connections (default: 20)\n * - DATABASE_APPLICATION_NAME: Postgres application_name (default: `svc=<productName>`)\n * - DATABASE_QUERY_TIMEOUT: opt-in client-side query timeout in ms — the\n * PgBouncer-safe query bound (default: OFF, preserving current behavior)\n * - DATABASE_STATEMENT_TIMEOUT / DATABASE_IDLE_IN_TRANSACTION_TIMEOUT / DATABASE_LOCK_TIMEOUT:\n * opt-in server-side timeouts in ms (default: OFF; DIRECT :5432 only — not\n * honored through the built-in PgBouncer :6432 runtime path)\n * - NODE_ENV: Environment for logging settings\n * - GRAPH_MIDDLEWARE_ENABLED: Enable graph sync (default: true)\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { createDatabaseClientFromEnv } from '@burdenoff/be-sdk/prisma';\n *\n * const { db } = createDatabaseClientFromEnv(PrismaClient, 'module-tags');\n * export { db };\n * ```\n */\nexport function createDatabaseClientFromEnv<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n productName: string,\n overrides?: Partial<DatabaseClientConfig>\n): DatabaseClient<T> {\n const databaseUrl = process.env['DATABASE_URL'];\n if (!databaseUrl) {\n throw new Error('DATABASE_URL environment variable is required');\n }\n\n const isDevelopment = process.env['NODE_ENV'] === 'development';\n\n const config: DatabaseClientConfig = {\n productName,\n databaseUrl,\n maxConnections: parseInt(process.env['DATABASE_MAX_CONNECTIONS'] || '20', 10),\n idleTimeoutMillis: parseInt(process.env['DATABASE_IDLE_TIMEOUT'] || '30000', 10),\n connectionTimeoutMillis: parseInt(process.env['DATABASE_CONNECTION_TIMEOUT'] || '10000', 10),\n ...resolvePoolTuningFromEnv(productName),\n enableQueryLogging: isDevelopment,\n slowQueryThreshold: isDevelopment ? 100 : 500,\n ...overrides,\n };\n\n // Transient acquire retry — env-tunable, and unlike the fields above zero is\n // meaningful (DATABASE_ACQUIRE_RETRIES=0 disables the retry entirely).\n const acquireRetriesRaw = process.env['DATABASE_ACQUIRE_RETRIES']?.trim();\n if (acquireRetriesRaw !== undefined && acquireRetriesRaw !== '' && config.acquireRetries === undefined) {\n const parsed = Number.parseInt(acquireRetriesRaw, 10);\n if (Number.isFinite(parsed) && parsed >= 0) {\n config.acquireRetries = parsed;\n }\n }\n const acquireRetryDelay = parsePositiveIntEnv('DATABASE_ACQUIRE_RETRY_DELAY');\n if (acquireRetryDelay !== undefined && config.acquireRetryDelayMillis === undefined) {\n config.acquireRetryDelayMillis = acquireRetryDelay;\n }\n\n return createDatabaseClient(PrismaClientConstructor, config);\n}\n","/**\n * Database Singleton Manager\n *\n * Provides a singleton pattern for database connections across microservices.\n * Services initialize once at startup and access the db instance globally.\n *\n * This eliminates the need for individual db.ts files in each microservice.\n *\n * @module prisma/manager\n * @category Database\n *\n * @example\n * ```typescript\n * // In your service's index.ts (startup)\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { initializeDatabase } from '@burdenoff/be-sdk/prisma';\n *\n * // Initialize once at startup\n * const { db, connect } = initializeDatabase(PrismaClient, 'module-tags');\n * await connect();\n *\n * // In any other file\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n * const db = getDb();\n * await db.client.user.findMany();\n * ```\n */\n\nimport { logger } from '../logger/index.js';\nimport {\n createDatabaseClient,\n createDatabaseClientFromEnv,\n type DatabaseClient,\n type DatabaseClientConfig,\n} from './factory.js';\nimport type { PrismaClientBase, PrismaClientConstructorOptions, DatabaseReturnType } from './client.js';\n\n/**\n * Global database manager state\n */\ninterface DatabaseManagerState {\n initialized: boolean;\n productName: string | null;\n client: DatabaseClient<PrismaClientBase> | null;\n}\n\n/**\n * Singleton state for the database manager\n */\nconst state: DatabaseManagerState = {\n initialized: false,\n productName: null,\n client: null,\n};\n\n/**\n * Initialize the database singleton\n *\n * Call this once at application startup with your service's PrismaClient.\n * After initialization, use `getDb()` to access the database anywhere.\n *\n * @param PrismaClientConstructor - The generated PrismaClient class from your service\n * @param productName - Product name for graph events (e.g., 'module-tags', 'workspaces')\n * @param config - Optional configuration overrides\n * @returns The database client with db, wrapper, connect, disconnect\n *\n * @throws Error if already initialized with a different product\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { initializeDatabase } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, connect, disconnect } = initializeDatabase(PrismaClient, 'module-tags');\n * await connect();\n * ```\n */\nexport function initializeDatabase<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n productName: string,\n config?: Partial<DatabaseClientConfig>\n): DatabaseClient<T> {\n // Check if already initialized\n if (state.initialized) {\n if (state.productName !== productName) {\n throw new Error(\n `Database already initialized for product \"${state.productName}\". ` +\n `Cannot reinitialize for \"${productName}\".`\n );\n }\n logger.debug('[DatabaseManager] Already initialized, returning existing client', { productName });\n return state.client as DatabaseClient<T>;\n }\n\n // Create the database client using env-based factory\n const client = createDatabaseClientFromEnv(PrismaClientConstructor, productName, config);\n\n // Store in singleton state\n state.initialized = true;\n state.productName = productName;\n state.client = client;\n\n logger.info('[DatabaseManager] Database initialized', { productName });\n\n return client;\n}\n\n/**\n * Initialize the database with explicit configuration\n *\n * Use this when you need full control over database configuration\n * rather than reading from environment variables.\n *\n * @param PrismaClientConstructor - The generated PrismaClient class\n * @param config - Full database configuration\n * @returns The database client\n *\n * @example\n * ```typescript\n * const { db } = initializeDatabaseWithConfig(PrismaClient, {\n * productName: 'module-tags',\n * databaseUrl: 'postgresql://...',\n * maxConnections: 50,\n * enableGraphExtension: false,\n * });\n * ```\n */\nexport function initializeDatabaseWithConfig<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n config: DatabaseClientConfig\n): DatabaseClient<T> {\n const { productName } = config;\n\n // Check if already initialized\n if (state.initialized) {\n if (state.productName !== productName) {\n throw new Error(\n `Database already initialized for product \"${state.productName}\". ` +\n `Cannot reinitialize for \"${productName}\".`\n );\n }\n logger.debug('[DatabaseManager] Already initialized, returning existing client', { productName });\n return state.client as DatabaseClient<T>;\n }\n\n // Create the database client\n const client = createDatabaseClient(PrismaClientConstructor, config);\n\n // Store in singleton state\n state.initialized = true;\n state.productName = productName;\n state.client = client;\n\n logger.info('[DatabaseManager] Database initialized with custom config', { productName });\n\n return client;\n}\n\n/**\n * Get the initialized database client\n *\n * Use this anywhere in your application to access the database.\n * Must call `initializeDatabase()` first at application startup.\n *\n * The returned client provides dynamic model access - you can access any\n * model property (e.g., `db.client.user`, `db.client.universalTag`) and\n * TypeScript will allow common Prisma operations (findMany, create, etc.).\n *\n * @returns The extended Prisma client (db) with dynamic model access\n * @throws Error if database not initialized\n *\n * @example\n * ```typescript\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n *\n * const db = getDb();\n * // Dynamic model access works without importing service-specific types\n * const tags = await db.client.universalTag.findMany();\n * const users = await db.client.user.findMany({ where: { active: true } });\n * ```\n */\nexport function getDb<T extends PrismaClientBase = PrismaClientBase>(): DatabaseReturnType<T> {\n if (!state.initialized || !state.client) {\n throw new Error('Database not initialized. Call initializeDatabase() at application startup before using getDb().');\n }\n return state.client.db as unknown as DatabaseReturnType<T>;\n}\n\n/**\n * Get the full database manager\n *\n * Returns the complete database client including wrapper, connect, and disconnect functions.\n * Useful when you need access to connection management utilities.\n *\n * @returns The full database client\n * @throws Error if database not initialized\n *\n * @example\n * ```typescript\n * import { getDatabaseManager } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, wrapper, connect, disconnect } = getDatabaseManager();\n * await connect();\n * ```\n */\nexport function getDatabaseManager<T extends PrismaClientBase = PrismaClientBase>(): DatabaseClient<T> {\n if (!state.initialized || !state.client) {\n throw new Error(\n 'Database not initialized. Call initializeDatabase() at application startup before using getDatabaseManager().'\n );\n }\n return state.client as DatabaseClient<T>;\n}\n\n/**\n * Check if database is initialized\n *\n * @returns True if database has been initialized\n *\n * @example\n * ```typescript\n * if (!isDatabaseInitialized()) {\n * await initializeDatabase(PrismaClient, 'my-service');\n * }\n * ```\n */\nexport function isDatabaseInitialized(): boolean {\n return state.initialized;\n}\n\n/**\n * Get the product name of the initialized database\n *\n * @returns The product name or null if not initialized\n */\nexport function getDatabaseProductName(): string | null {\n return state.productName;\n}\n\n/**\n * Reset the database manager (for testing purposes only)\n *\n * WARNING: This disconnects and resets the database manager.\n * Only use this in test environments for cleanup between tests.\n *\n * @internal\n */\nexport async function resetDatabaseManager(): Promise<void> {\n if (state.client) {\n try {\n await state.client.disconnect();\n } catch (error) {\n logger.warn('[DatabaseManager] Error during disconnect on reset', { error });\n }\n }\n\n state.initialized = false;\n state.productName = null;\n state.client = null;\n\n logger.debug('[DatabaseManager] Database manager reset');\n}\n","/**\n * Prisma Health Check Utilities\n */\n\nimport { logger } from '../logger/index.js';\nimport type { DatabaseHealth } from './types.js';\nimport type { PrismaClientBase } from './client.js';\n\n/**\n * Check database health\n */\nexport async function checkDatabaseHealth<T extends PrismaClientBase>(client: T): Promise<DatabaseHealth> {\n try {\n const start = Date.now();\n await client.$queryRaw`SELECT 1`;\n const latency = Date.now() - start;\n\n return { healthy: true, latency };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error('[Prisma] Health check failed', { error: errorMessage });\n\n return {\n healthy: false,\n error: errorMessage,\n };\n }\n}\n\n/**\n * Test database connection\n */\nexport async function testConnection<T extends PrismaClientBase>(client: T): Promise<boolean> {\n try {\n await client.$queryRaw`SELECT 1`;\n return true;\n } catch (error) {\n logger.error('[Prisma] Connection test failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\n }\n}\n\n/**\n * Get database version\n */\nexport async function getDatabaseVersion<T extends PrismaClientBase>(client: T): Promise<string | null> {\n try {\n const result = await client.$queryRaw<Array<{ version?: string }>>`SELECT version()`;\n return result[0]?.version ?? null;\n } catch (error) {\n logger.error('[Prisma] Failed to get database version', {\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n}\n\n/**\n * Get database stats\n */\nexport async function getDatabaseStats<T extends PrismaClientBase>(\n client: T\n): Promise<{\n health: DatabaseHealth;\n version: string | null;\n timestamp: Date;\n}> {\n const [health, version] = await Promise.all([checkDatabaseHealth(client), getDatabaseVersion(client)]);\n\n return {\n health,\n version,\n timestamp: new Date(),\n };\n}\n","/**\n * Prisma Field Extraction Utilities\n *\n * Provides utilities for extracting model fields from Prisma schema.\n * In Prisma 7, DMMF is not available at runtime, so this module provides\n * build-time field extraction through a generator.\n *\n * @module prisma/fields\n */\n\nimport { createRequire } from 'node:module';\nimport { logger } from '../logger/index.js';\n\nconst requireFn = createRequire(import.meta.url);\n\n/**\n * Field extraction options\n */\nexport interface FieldExtractionOptions {\n /** Fields to exclude from extraction */\n excludeFields?: string[];\n /** Whether to include relation fields */\n includeRelations?: boolean;\n /** Custom filter function */\n customFilter?: (field: { name: string; type: string; isRelation: boolean }) => boolean;\n}\n\n/**\n * Field extraction result\n */\nexport interface FieldExtractionResult {\n /** Extracted field names */\n fields: string[];\n /** Metadata about the extraction */\n metadata: {\n /** Total number of fields found */\n totalFields: number;\n /** Number of fields excluded */\n excludedCount: number;\n /** Names of excluded fields */\n excludedFields: string[];\n /** Number of relation fields */\n relationFields: number;\n };\n}\n\n/**\n * Model fields mapping\n * This will be generated at build time by the Prisma generator\n */\nexport type ModelFieldsMap = Record<\n string,\n {\n fields: string[];\n relations: string[];\n }\n>;\n\n/**\n * Import generated fields from the consuming package\n * This function should be used by backends to load their generated fields\n */\nexport function loadGeneratedFields(generatedFieldsPath: string): ModelFieldsMap {\n try {\n // Dynamic import of generated fields using createRequire\n const generated = requireFn(generatedFieldsPath) as { default: ModelFieldsMap };\n return generated.default || generated;\n } catch (error) {\n logger.error('[Prisma] Failed to load generated fields', {\n error: error instanceof Error ? error.message : String(error),\n path: generatedFieldsPath,\n });\n throw new Error(`Failed to load generated fields from ${generatedFieldsPath}`);\n }\n}\n\n/**\n * Extract fields from generated model fields with options\n */\nexport function extractFieldsFromModel(\n modelName: string,\n modelFieldsMap: ModelFieldsMap,\n options: FieldExtractionOptions = {}\n): FieldExtractionResult {\n const modelFields = modelFieldsMap[modelName];\n\n if (!modelFields) {\n throw new Error(\n `Model \"${modelName}\" not found in generated fields. ` +\n `Available models: ${Object.keys(modelFieldsMap).join(', ')}`\n );\n }\n\n const { excludeFields = [], includeRelations = false, customFilter } = options;\n\n // Start with scalar fields\n let fields = [...modelFields.fields];\n\n // Add relations if requested\n if (includeRelations) {\n fields = [...fields, ...modelFields.relations];\n }\n\n // Track excluded fields\n const excluded: string[] = [];\n\n // Apply exclusions\n if (excludeFields.length > 0) {\n fields = fields.filter((field) => {\n if (excludeFields.includes(field)) {\n excluded.push(field);\n return false;\n }\n return true;\n });\n }\n\n // Apply custom filter\n if (customFilter) {\n fields = fields.filter((fieldName) => {\n const isRelation = modelFields.relations.includes(fieldName);\n const shouldInclude = customFilter({\n name: fieldName,\n type: 'unknown', // Type information not available without full DMMF\n isRelation,\n });\n\n if (!shouldInclude) {\n excluded.push(fieldName);\n }\n\n return shouldInclude;\n });\n }\n\n return {\n fields,\n metadata: {\n totalFields: modelFields.fields.length + modelFields.relations.length,\n excludedCount: excluded.length,\n excludedFields: excluded,\n relationFields: modelFields.relations.length,\n },\n };\n}\n\n/**\n * Get all field names for a model (without options)\n */\nexport function getModelFields(modelName: string, modelFieldsMap: ModelFieldsMap, includeRelations = false): string[] {\n const result = extractFieldsFromModel(modelName, modelFieldsMap, { includeRelations });\n return result.fields;\n}\n\n/**\n * Check if a model exists in the generated fields\n */\nexport function hasModel(modelName: string, modelFieldsMap: ModelFieldsMap): boolean {\n return modelName in modelFieldsMap;\n}\n\n/**\n * Get all available model names\n */\nexport function getAllModelNames(modelFieldsMap: ModelFieldsMap): string[] {\n return Object.keys(modelFieldsMap);\n}\n","/**\n * Prisma Context Filtering Utilities\n *\n * Utilities for handling operation context in queries, mutations, and filtering.\n * Context JSON enables multi-dimensional data isolation across workspaces, users, projects, etc.\n *\n * @module prisma/context\n * @category Database\n */\n\nimport { isSameProductSlug, productSlugVariants } from '../product-alias/index.js';\n\n/**\n * Context filter input for querying entities by context\n */\nexport interface ContextFilterInput {\n workspaceId?: string | null;\n userId?: string | null;\n projectId?: string | null;\n appId?: string | null;\n /** Product identifier (e.g. \"vibecontrols\", \"workspaces\"). Stamped on cross-product\n * records so admin filters can scope by originating product. */\n productId?: string | null;\n /** Organization identifier within the tenant. */\n organizationId?: string | null;\n}\n\n/**\n * Operation context for create/update operations\n */\nexport interface OperationContext extends ContextFilterInput {\n custom?: Record<string, unknown> | null;\n}\n\n/**\n * Prisma JSON filter type (simplified for context filtering)\n * This type is designed to be compatible with Prisma's JsonNullableFilter\n * Uses Record<string, unknown> for maximum compatibility with various Prisma versions\n */\nexport type PrismaJsonFilter = Record<string, unknown>;\n\n/**\n * One entry of {@link buildContextWhereConditions}: a JSON-path predicate on `context`,\n * or an `OR` of them (used for a renamed product's slug twins).\n */\nexport type ContextWhereCondition = { context: PrismaJsonFilter } | { OR: Array<{ context: PrismaJsonFilter }> };\n\n/**\n * JSON value type for Prisma (includes null for reading from DB)\n */\nexport type JsonValue = string | number | boolean | null | { [key: string]: JsonValue } | JsonValue[];\n\n/**\n * Input JSON value type for Prisma (excludes null for writing to DB)\n * Compatible with Prisma's InputJsonValue type\n */\nexport type InputJsonValue = string | number | boolean | { [key: string]: InputJsonValue } | InputJsonValue[];\n\n/**\n * Build Prisma where condition for context filtering.\n * Uses PostgreSQL JSONB containment operators for efficient queries.\n *\n * @param contextFilter - The context filter input\n * @returns Prisma where clause for context field, or undefined if no filter provided\n *\n * @example\n * ```typescript\n * const contextWhere = buildContextWhereClause({\n * workspaceId: '123',\n * projectId: '456'\n * });\n * // Returns: { path: ['workspaceId'], equals: '123' }\n * ```\n */\nexport function buildContextWhereClause(\n contextFilter: ContextFilterInput | null | undefined\n): PrismaJsonFilter | undefined {\n if (!contextFilter) {\n return undefined;\n }\n\n // Build array of path conditions for each non-null field\n const conditions: PrismaJsonFilter[] = [];\n\n if (contextFilter.workspaceId != null) {\n conditions.push({\n path: ['workspaceId'],\n equals: contextFilter.workspaceId,\n });\n }\n\n if (contextFilter.userId != null) {\n conditions.push({\n path: ['userId'],\n equals: contextFilter.userId,\n });\n }\n\n if (contextFilter.projectId != null) {\n conditions.push({\n path: ['projectId'],\n equals: contextFilter.projectId,\n });\n }\n\n if (contextFilter.appId != null) {\n conditions.push({\n path: ['appId'],\n equals: contextFilter.appId,\n });\n }\n\n if (contextFilter.productId != null) {\n conditions.push({\n path: ['productId'],\n equals: contextFilter.productId,\n });\n }\n\n if (contextFilter.organizationId != null) {\n conditions.push({\n path: ['organizationId'],\n equals: contextFilter.organizationId,\n });\n }\n\n // If no conditions, return undefined\n if (conditions.length === 0) {\n return undefined;\n }\n\n // If single condition, return it directly\n if (conditions.length === 1) {\n return conditions[0];\n }\n\n // For multiple conditions, return the first one\n // Caller should use buildContextWhereConditions for multiple AND conditions\n return conditions[0];\n}\n\n/**\n * Build context where conditions as an array for use in AND clause.\n * This is useful when you need to filter by multiple context fields.\n *\n * @param contextFilter - The context filter input\n * @returns Array of Prisma where conditions, each targeting the context field\n *\n * @example\n * ```typescript\n * const conditions = buildContextWhereConditions({\n * workspaceId: '123',\n * projectId: '456'\n * });\n * // Use in Prisma query:\n * prisma.entity.findMany({\n * where: { AND: conditions }\n * });\n * ```\n */\nexport function buildContextWhereConditions(\n contextFilter: ContextFilterInput | null | undefined\n): ContextWhereCondition[] {\n if (!contextFilter) {\n return [];\n }\n\n const conditions: ContextWhereCondition[] = [];\n\n if (contextFilter.workspaceId != null) {\n conditions.push({\n context: {\n path: ['workspaceId'],\n equals: contextFilter.workspaceId,\n },\n });\n }\n\n if (contextFilter.userId != null) {\n conditions.push({\n context: {\n path: ['userId'],\n equals: contextFilter.userId,\n },\n });\n }\n\n if (contextFilter.projectId != null) {\n conditions.push({\n context: {\n path: ['projectId'],\n equals: contextFilter.projectId,\n },\n });\n }\n\n if (contextFilter.appId != null) {\n conditions.push({\n context: {\n path: ['appId'],\n equals: contextFilter.appId,\n },\n });\n }\n\n if (contextFilter.productId != null) {\n // A renamed product (botlit → botmanor) matches rows stored under either slug while\n // they are migrated; every other product keeps the exact single-slug predicate.\n const slugs = productSlugVariants(contextFilter.productId);\n if (slugs.length > 1) {\n conditions.push({\n OR: slugs.map((slug) => ({ context: { path: ['productId'], equals: slug } })),\n });\n } else {\n conditions.push({\n context: {\n path: ['productId'],\n equals: contextFilter.productId,\n },\n });\n }\n }\n\n if (contextFilter.organizationId != null) {\n conditions.push({\n context: {\n path: ['organizationId'],\n equals: contextFilter.organizationId,\n },\n });\n }\n\n return conditions;\n}\n\n/**\n * Convert context input to Prisma JSON format for create/update operations.\n *\n * @param contextInput - The context input\n * @returns JSON value for the context field, or undefined if empty\n *\n * @example\n * ```typescript\n * const contextJson = toContextJson({\n * workspaceId: '123',\n * userId: '456'\n * });\n * // Use in Prisma create:\n * prisma.entity.create({\n * data: { context: contextJson }\n * });\n * ```\n */\nexport function toContextJson(contextInput: OperationContext | null | undefined): InputJsonValue | undefined {\n if (!contextInput) {\n return undefined;\n }\n\n // Remove null values and build clean context object\n const context: Record<string, InputJsonValue> = {};\n\n if (contextInput.workspaceId != null) {\n context['workspaceId'] = contextInput.workspaceId;\n }\n if (contextInput.userId != null) {\n context['userId'] = contextInput.userId;\n }\n if (contextInput.projectId != null) {\n context['projectId'] = contextInput.projectId;\n }\n if (contextInput.appId != null) {\n context['appId'] = contextInput.appId;\n }\n if (contextInput.productId != null) {\n context['productId'] = contextInput.productId;\n }\n if (contextInput.organizationId != null) {\n context['organizationId'] = contextInput.organizationId;\n }\n if (contextInput.custom != null) {\n context['custom'] = contextInput.custom as InputJsonValue;\n }\n\n // Return undefined if no fields set\n if (Object.keys(context).length === 0) {\n return undefined;\n }\n\n return context;\n}\n\n/**\n * Filter out null values from an object for Prisma compatibility\n */\nfunction filterNullValues(obj: Record<string, unknown>): Record<string, InputJsonValue> {\n const filtered: Record<string, InputJsonValue> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== null) {\n filtered[key] = value as InputJsonValue;\n }\n }\n return filtered;\n}\n\n/**\n * Merge a single field into the merged context object\n */\nfunction mergeContextField(\n merged: Record<string, InputJsonValue>,\n fieldName: string,\n fieldValue: string | Record<string, unknown> | null | undefined\n): void {\n if (fieldValue === undefined) {\n return; // Don't touch this field\n }\n\n if (fieldValue === null) {\n delete merged[fieldName]; // Explicitly remove\n } else {\n merged[fieldName] = fieldValue as InputJsonValue; // Set new value\n }\n}\n\n/**\n * Merge existing context with new context input.\n * New values override existing ones, but undefined values are preserved from existing.\n *\n * @param existingContext - The existing context JSON from database\n * @param newContext - The new context input\n * @returns Merged context as InputJsonValue (suitable for Prisma writes)\n *\n * @example\n * ```typescript\n * const merged = mergeContext(\n * { workspaceId: '123', userId: 'old' },\n * { userId: 'new', projectId: '456' }\n * );\n * // Result: { workspaceId: '123', userId: 'new', projectId: '456' }\n * ```\n */\nexport function mergeContext(\n existingContext: JsonValue | null | undefined,\n newContext: OperationContext | null | undefined\n): InputJsonValue | undefined {\n // If no new context, return existing (excluding null values)\n if (!newContext) {\n if (!existingContext) {\n return undefined;\n }\n // Filter out null values from existing context for Prisma compatibility\n if (typeof existingContext === 'object' && !Array.isArray(existingContext)) {\n const filtered = filterNullValues(existingContext);\n return Object.keys(filtered).length > 0 ? filtered : undefined;\n }\n return existingContext as InputJsonValue;\n }\n\n // If no existing context, convert new to JSON\n if (!existingContext || typeof existingContext !== 'object' || Array.isArray(existingContext)) {\n return toContextJson(newContext);\n }\n\n // Merge existing with new\n const merged = filterNullValues(existingContext);\n\n // Merge each field from new context\n mergeContextField(merged, 'workspaceId', newContext.workspaceId);\n mergeContextField(merged, 'userId', newContext.userId);\n mergeContextField(merged, 'projectId', newContext.projectId);\n mergeContextField(merged, 'appId', newContext.appId);\n mergeContextField(merged, 'productId', newContext.productId);\n mergeContextField(merged, 'organizationId', newContext.organizationId);\n mergeContextField(merged, 'custom', newContext.custom);\n\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\n/**\n * Parse context JSON from database to OperationContext interface.\n *\n * @param contextJson - The context JSON from database\n * @returns Parsed OperationContext or null\n *\n * @example\n * ```typescript\n * const context = parseContext(entity.context);\n * if (context?.workspaceId) {\n * // Use workspace-specific logic\n * }\n * ```\n */\nexport function parseContext(contextJson: JsonValue | null | undefined): OperationContext | null {\n if (!contextJson || typeof contextJson !== 'object' || Array.isArray(contextJson)) {\n return null;\n }\n\n const ctx = contextJson as Record<string, unknown>;\n\n return {\n workspaceId: typeof ctx['workspaceId'] === 'string' ? ctx['workspaceId'] : null,\n userId: typeof ctx['userId'] === 'string' ? ctx['userId'] : null,\n projectId: typeof ctx['projectId'] === 'string' ? ctx['projectId'] : null,\n appId: typeof ctx['appId'] === 'string' ? ctx['appId'] : null,\n productId: typeof ctx['productId'] === 'string' ? ctx['productId'] : null,\n organizationId: typeof ctx['organizationId'] === 'string' ? ctx['organizationId'] : null,\n custom: typeof ctx['custom'] === 'object' ? (ctx['custom'] as Record<string, unknown>) : null,\n };\n}\n\n/**\n * Check if context matches filter criteria\n *\n * @param context - The context to check\n * @param filter - The filter criteria\n * @returns True if context matches all filter criteria\n */\nexport function contextMatches(context: OperationContext | null | undefined, filter: ContextFilterInput): boolean {\n if (!context) {\n return false;\n }\n\n if (filter.workspaceId != null && context.workspaceId !== filter.workspaceId) {\n return false;\n }\n if (filter.userId != null && context.userId !== filter.userId) {\n return false;\n }\n if (filter.projectId != null && context.projectId !== filter.projectId) {\n return false;\n }\n if (filter.appId != null && context.appId !== filter.appId) {\n return false;\n }\n // Renamed products (botlit → botmanor) match under either slug while rows are migrated.\n if (filter.productId != null && !isSameProductSlug(context.productId, filter.productId)) {\n return false;\n }\n if (filter.organizationId != null && context.organizationId !== filter.organizationId) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Create a default context from SDK context\n *\n * @param sdkContext - The SDK context (from AsyncLocalStorage)\n * @returns Operation context with workspace and user info\n */\nexport function createContextFromSDK(sdkContext: {\n workspaceId?: string;\n userId?: string;\n projectId?: string;\n appId?: string;\n productId?: string;\n organizationId?: string;\n}): OperationContext {\n return {\n workspaceId: sdkContext.workspaceId ?? null,\n userId: sdkContext.userId ?? null,\n projectId: sdkContext.projectId ?? null,\n appId: sdkContext.appId ?? null,\n productId: sdkContext.productId ?? null,\n organizationId: sdkContext.organizationId ?? null,\n };\n}\n","/**\n * Prisma Module for Burdenoff Backend SDK\n *\n * Provides Prisma 7 utilities including:\n * - Singleton database manager for microservices\n * - Unified database client factory with graph extension\n * - Prisma client configuration with PostgreSQL adapter\n * - Connection pooling and management\n * - Health checks and monitoring\n * - Graceful shutdown handling\n * - Field extraction utilities for graph sync\n * - Context filtering utilities for multi-tenant queries\n * - Workspace extension for automatic workspaceId injection\n *\n * @module prisma\n * @category Database\n */\n\nexport * from './manager.js';\nexport * from './factory.js';\nexport * from './client.js';\nexport type * from './types.js';\nexport * from './health.js';\nexport * from './fields.js';\nexport * from './context.js';\nexport * from './workspace-extension.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8GA,SAAS,iCAAiC,aAA8B;CACtE,MAAM,WAAW,QAAQ,IAAI;CAC7B,IAAI,aAAa,QAAQ,OAAO;CAChC,IAAI,aAAa,SAAS,OAAO;CAEjC,MAAM,QAAQ,QAAQ,IAAI,kBAAkB,EAAE,YAAY;CAC1D,IAAI,UAAU,UAAU,OAAO;CAC/B,IAAI,UAAU,UAAU,OAAO;CAE/B,MAAM,OAAO,YAAY,YAAY;CACrC,IAAI,KAAK,WAAW,SAAS,KAAK,KAAK,WAAW,SAAS,GAAG,OAAO;CACrE,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,qBACd,yBACA,QACmB;CACnB,MAAM,EACJ,aACA,uBAAuB,QAAQ,IAAI,gCAAgC,SACnE,mBACA,2BAA2B,iCAAiC,WAAW,GACvE,0BACA,2BAA2B,MAC3B,GAAG,iBACD;CAOJ,MAAM,2BAA+C;EACnD,GAAG;EACH,iBAAiB,aAAa,mBAAmB,OAAO;CAC1D;CAIA,6BAA6B,WAAW;CAGxC,MAAM,UAAU,mBAAmB,yBAAyB,wBAAwB;CAGpF,MAAM,aAAa,QAAQ,UAAU;CAWrC,IAAI;CAGJ,IAAI,sBAAsB;EAGxB,MAAM,cA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OAAO,OAAO,IAAI,aAAa,WAAW,IAAI,WAAW;EACzD,WAAW,OAAO,IAAI,iBAAiB,WAAW,IAAI,eAAe;EACrE,gBAAgB,OAAO,IAAI,sBAAsB,WAAW,IAAI,oBAAoB;EACpF,QAAQ,OAAO,IAAI,cAAc,WAAY,IAAI,YAAwC;CAC3F;AACF;;;;;;;;AASA,SAAgB,eAAe,SAA8C,QAAqC;CAChH,IAAI,CAAC,SACH,OAAO;CAGT,IAAI,OAAO,eAAe,QAAQ,QAAQ,gBAAgB,OAAO,aAC/D,OAAO;CAET,IAAI,OAAO,UAAU,QAAQ,QAAQ,WAAW,OAAO,QACrD,OAAO;CAET,IAAI,OAAO,aAAa,QAAQ,QAAQ,cAAc,OAAO,WAC3D,OAAO;CAET,IAAI,OAAO,SAAS,QAAQ,QAAQ,UAAU,OAAO,OACnD,OAAO;CAGT,IAAI,OAAO,aAAa,QAAQ,CAAC,kBAAkB,QAAQ,WAAW,OAAO,SAAS,GACpF,OAAO;CAET,IAAI,OAAO,kBAAkB,QAAQ,QAAQ,mBAAmB,OAAO,gBACrE,OAAO;CAGT,OAAO;AACT;;;;;;;AAQA,SAAgB,qBAAqB,YAOhB;CACnB,OAAO;EACL,aAAa,WAAW,eAAe;EACvC,QAAQ,WAAW,UAAU;EAC7B,WAAW,WAAW,aAAa;EACnC,OAAO,WAAW,SAAS;EAC3B,WAAW,WAAW,aAAa;EACnC,gBAAgB,WAAW,kBAAkB;CAC/C;AACF"}
1
+ {"version":3,"file":"prisma-CUij0pph.js","names":[],"sources":["../src/prisma/factory.ts","../src/prisma/manager.ts","../src/prisma/health.ts","../src/prisma/fields.ts","../src/prisma/context.ts","../src/prisma/index.ts"],"sourcesContent":["/**\n * Database Client Factory\n *\n * Provides a unified factory for creating fully-configured database clients\n * with Prisma 7, PostgreSQL adapter, graph extension, and graceful shutdown.\n *\n * This module consolidates all database setup into a single call, reducing\n * boilerplate across all backend services.\n *\n * @module prisma/factory\n * @category Database\n */\n\nimport { logger } from '../logger/index.js';\nimport {\n createPrismaClient,\n ensureServiceApplicationName,\n type PrismaClientBase,\n type PrismaClientWrapper,\n type PrismaClientConstructorOptions,\n} from './client.js';\nimport type { PrismaClientConfig } from './types.js';\nimport { addGraphExtension, type GraphMiddlewareConfig, type GraphEventEmitter } from '../graph/middleware/index.js';\nimport { getGraphEventEmitter } from '../event-queue/graph-emitter.js';\nimport { addWorkspaceExtension, type WorkspaceExtensionConfig } from './workspace-extension.js';\n\n/**\n * Configuration for creating a database client\n */\nexport interface DatabaseClientConfig extends PrismaClientConfig {\n /**\n * Product name for graph events (e.g., 'module-tags', 'workspaces')\n */\n productName: string;\n\n /**\n * Enable graph extension for entity sync\n * @default true (reads from GRAPH_MIDDLEWARE_ENABLED env var)\n */\n enableGraphExtension?: boolean;\n\n /**\n * Custom graph event emitter (defaults to NATS-based emitter)\n */\n graphEventEmitter?: GraphEventEmitter;\n\n /**\n * Enable workspace extension for automatic workspaceId injection.\n *\n * Default is layer-aware:\n * - Global-layer services (`productName` starting with `global-` or `global_`,\n * or `WORKSPACE_LAYER=global`) default to `false`. Global-layer tables\n * (Tenant, Organization, Workspace, PlatformProduct, etc.) are intentionally\n * not workspace-scoped — enforcing workspaceId on them would block legitimate\n * queries like `myOrganizations`, `myWorkspaces`, `myAccessibleProducts`.\n * - All other services (wspace layer, product backends) default to `true`.\n *\n * `WORKSPACE_EXTENSION_ENABLED` env var always wins when explicitly set\n * (`true` or `false`). Pass the field on `config` for code-level override.\n */\n enableWorkspaceExtension?: boolean;\n\n /**\n * Configuration for the workspace extension\n */\n workspaceExtensionConfig?: WorkspaceExtensionConfig;\n\n /**\n * Register process shutdown handlers for graceful shutdown\n * @default true\n */\n registerShutdownHandlers?: boolean;\n}\n\n/**\n * Result of creating a database client\n */\nexport interface DatabaseClient<T extends PrismaClientBase> {\n /**\n * The extended Prisma client for database operations\n * Use this for all queries: db.model.operation()\n */\n db: T & { client: T };\n\n /**\n * The Prisma client wrapper with connection management utilities\n */\n wrapper: PrismaClientWrapper<T>;\n\n /**\n * Connect to the database with retry logic\n */\n connect: (retries?: number, delay?: number) => Promise<void>;\n\n /**\n * Disconnect from the database\n */\n disconnect: () => Promise<void>;\n}\n\n/**\n * Layer-aware default for the workspace extension.\n *\n * Global-layer services (productName starting with `global-`/`global_`, or\n * `WORKSPACE_LAYER=global`) opt out by default because their tables don't carry\n * a workspaceId column — enforcement would break queries like `myOrganizations`,\n * `myAccessibleProducts`, `contentPages`.\n *\n * `WORKSPACE_EXTENSION_ENABLED` is respected as an explicit override.\n */\nfunction resolveWorkspaceExtensionDefault(productName: string): boolean {\n const explicit = process.env['WORKSPACE_EXTENSION_ENABLED'];\n if (explicit === 'true') return true;\n if (explicit === 'false') return false;\n\n const layer = process.env['WORKSPACE_LAYER']?.toLowerCase();\n if (layer === 'global') return false;\n if (layer === 'wspace') return true;\n\n const name = productName.toLowerCase();\n if (name.startsWith('global-') || name.startsWith('global_')) return false;\n return true;\n}\n\n/**\n * Create a fully-configured database client with graph extension\n *\n * This is the recommended way to create a database connection in all backend services.\n * It handles:\n * - Prisma client creation with PostgreSQL adapter\n * - Connection pooling configuration\n * - Query logging (in development)\n * - Graph extension for entity sync (via NATS or in-memory)\n * - Graceful shutdown handlers\n *\n * @example\n * ```typescript\n * // In your service's db.ts\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { createDatabaseClient } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, wrapper, connect, disconnect } = createDatabaseClient(PrismaClient, {\n * productName: 'my-service',\n * databaseUrl: process.env.DATABASE_URL!,\n * });\n *\n * export { db, wrapper, connect, disconnect };\n * export type ExtendedPrismaClient = typeof db;\n * ```\n *\n * @example\n * ```typescript\n * // With custom configuration\n * const { db } = createDatabaseClient(PrismaClient, {\n * productName: 'workspaces',\n * databaseUrl: process.env.DATABASE_URL!,\n * maxConnections: 50,\n * enableQueryLogging: true,\n * slowQueryThreshold: 200,\n * enableGraphExtension: true,\n * registerShutdownHandlers: true,\n * });\n * ```\n */\nexport function createDatabaseClient<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n config: DatabaseClientConfig\n): DatabaseClient<T> {\n const {\n productName,\n enableGraphExtension = process.env['GRAPH_MIDDLEWARE_ENABLED'] !== 'false',\n graphEventEmitter,\n enableWorkspaceExtension = resolveWorkspaceExtensionDefault(productName),\n workspaceExtensionConfig,\n registerShutdownHandlers = true,\n ...prismaConfig\n } = config;\n\n // Tag every service's pool with `svc=<productName>` by default so its\n // connections are attributable in pg_stat_activity / pg_stat_statements\n // (the on-ramp to per-workspace observability and shard routing). This is\n // pure diagnostic metadata with no effect on behavior; explicit\n // `applicationName` on the config always wins.\n const prismaConfigWithDefaults: PrismaClientConfig = {\n ...prismaConfig,\n applicationName: prismaConfig.applicationName ?? `svc=${productName}`,\n };\n\n // Belt-and-suspenders: also set the PGAPPNAME env fallback so any additional\n // pools this service opens outside be-sdk still carry the per-service tag.\n ensureServiceApplicationName(productName);\n\n // Create Prisma client wrapper\n const wrapper = createPrismaClient(PrismaClientConstructor, prismaConfigWithDefaults);\n\n // Get the base client\n const baseClient = wrapper.getClient();\n\n // Extension chaining order:\n // 1. Graph extension (event emission on CRUD) - runs first\n // 2. Workspace extension (auto-inject workspaceId) - runs second\n //\n // The workspace extension should run BEFORE graph extension in the\n // interception chain so that graph events include the injected workspaceId.\n // In Prisma $extends, the LAST extension added runs FIRST (outermost wrapper).\n // So we add graph first, then workspace on top.\n\n let extendedClient: T;\n\n // Step 1: Add graph extension\n if (enableGraphExtension) {\n const eventEmitter = graphEventEmitter ?? getGraphEventEmitter();\n\n const graphConfig: GraphMiddlewareConfig = {\n enabled: true,\n productName,\n eventEmitter,\n };\n\n extendedClient = addGraphExtension(baseClient, graphConfig);\n\n logger.info('[Database] Graph extension enabled', { productName });\n } else {\n extendedClient = baseClient;\n logger.info('[Database] Graph extension disabled');\n }\n\n // Step 2: Add workspace extension (wraps on top of graph)\n if (enableWorkspaceExtension) {\n extendedClient = addWorkspaceExtension(extendedClient, workspaceExtensionConfig);\n\n logger.info('[Database] Workspace extension enabled', { productName });\n } else {\n logger.info('[Database] Workspace extension disabled');\n }\n\n // Add backwards compatibility alias\n const db = extendedClient as T & { client: T };\n (db as unknown as Record<string, unknown>)['client'] = db;\n\n // Register shutdown handlers if requested\n if (registerShutdownHandlers) {\n wrapper.registerShutdownHandlers();\n logger.debug('[Database] Shutdown handlers registered');\n }\n\n return {\n db,\n wrapper,\n connect: (retries?: number, delay?: number) => wrapper.connect(retries, delay),\n disconnect: () => wrapper.disconnect(),\n };\n}\n\n/**\n * Pool-tuning options resolved from environment variables.\n */\nexport interface PoolTuningEnv {\n /** Postgres application_name (defaults to `svc=<productName>`). */\n applicationName: string;\n /** Client-side node-postgres query_timeout in ms, if opted in (pooler-safe). */\n queryTimeoutMillis?: number;\n /** Server-side statement_timeout in ms, if opted in. */\n statementTimeoutMillis?: number;\n /** Server-side idle_in_transaction_session_timeout in ms, if opted in. */\n idleInTransactionTimeoutMillis?: number;\n /** Server-side lock_timeout in ms, if opted in. */\n lockTimeoutMillis?: number;\n}\n\n/**\n * Parse a strictly-positive integer environment variable.\n *\n * Returns `undefined` for unset, empty, non-numeric, zero, or negative values —\n * so a misconfigured or absent env var can never silently enable an aggressive\n * (or nonsensical) timeout. This is what keeps the DB-enforced timeouts OFF by\n * default and therefore behavior-preserving.\n */\nfunction parsePositiveIntEnv(name: string): number | undefined {\n const raw = process.env[name];\n if (raw == null || raw.trim() === '') {\n return undefined;\n }\n const parsed = Number.parseInt(raw.trim(), 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\n/**\n * Resolve pool tuning (application_name + opt-in DB timeouts) from env vars:\n * - DATABASE_APPLICATION_NAME: overrides the default `svc=<productName>` tag\n * - DATABASE_QUERY_TIMEOUT: client-side node-postgres query_timeout in ms (opt-in, pooler-safe)\n * - DATABASE_STATEMENT_TIMEOUT: server-side statement_timeout in ms (opt-in; DIRECT :5432 only — see note)\n * - DATABASE_IDLE_IN_TRANSACTION_TIMEOUT: idle_in_transaction_session_timeout in ms (opt-in)\n * - DATABASE_LOCK_TIMEOUT: lock_timeout in ms (opt-in)\n *\n * Timeouts are omitted entirely unless explicitly set to a positive integer, so\n * the default is exactly today's behavior (no timeouts).\n *\n * NOTE: prefer `DATABASE_QUERY_TIMEOUT` for services whose `DATABASE_URL` points\n * at the built-in PgBouncer (`:6432`). `DATABASE_STATEMENT_TIMEOUT` and friends\n * are Postgres startup parameters that Azure PgBouncer does not pass through, so\n * they silently have no effect (or fail the connection) on the pooled path.\n */\nexport function resolvePoolTuningFromEnv(productName: string): PoolTuningEnv {\n const tuning: PoolTuningEnv = {\n applicationName: process.env['DATABASE_APPLICATION_NAME']?.trim() || `svc=${productName}`,\n };\n\n const queryTimeout = parsePositiveIntEnv('DATABASE_QUERY_TIMEOUT');\n if (queryTimeout !== undefined) {\n tuning.queryTimeoutMillis = queryTimeout;\n }\n\n const statementTimeout = parsePositiveIntEnv('DATABASE_STATEMENT_TIMEOUT');\n if (statementTimeout !== undefined) {\n tuning.statementTimeoutMillis = statementTimeout;\n }\n\n const idleInTransactionTimeout = parsePositiveIntEnv('DATABASE_IDLE_IN_TRANSACTION_TIMEOUT');\n if (idleInTransactionTimeout !== undefined) {\n tuning.idleInTransactionTimeoutMillis = idleInTransactionTimeout;\n }\n\n const lockTimeout = parsePositiveIntEnv('DATABASE_LOCK_TIMEOUT');\n if (lockTimeout !== undefined) {\n tuning.lockTimeoutMillis = lockTimeout;\n }\n\n return tuning;\n}\n\n/**\n * Create a database client from environment variables\n *\n * Convenience function that reads configuration from standard environment variables:\n * - DATABASE_URL: Connection string (required)\n * - DATABASE_MAX_CONNECTIONS: Max pool connections (default: 20)\n * - DATABASE_APPLICATION_NAME: Postgres application_name (default: `svc=<productName>`)\n * - DATABASE_QUERY_TIMEOUT: opt-in client-side query timeout in ms — the\n * PgBouncer-safe query bound (default: OFF, preserving current behavior)\n * - DATABASE_STATEMENT_TIMEOUT / DATABASE_IDLE_IN_TRANSACTION_TIMEOUT / DATABASE_LOCK_TIMEOUT:\n * opt-in server-side timeouts in ms (default: OFF; DIRECT :5432 only — not\n * honored through the built-in PgBouncer :6432 runtime path)\n * - NODE_ENV: Environment for logging settings\n * - GRAPH_MIDDLEWARE_ENABLED: Enable graph sync (default: true)\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { createDatabaseClientFromEnv } from '@burdenoff/be-sdk/prisma';\n *\n * const { db } = createDatabaseClientFromEnv(PrismaClient, 'module-tags');\n * export { db };\n * ```\n */\nexport function createDatabaseClientFromEnv<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n productName: string,\n overrides?: Partial<DatabaseClientConfig>\n): DatabaseClient<T> {\n const databaseUrl = process.env['DATABASE_URL'];\n if (!databaseUrl) {\n throw new Error('DATABASE_URL environment variable is required');\n }\n\n const isDevelopment = process.env['NODE_ENV'] === 'development';\n\n const config: DatabaseClientConfig = {\n productName,\n databaseUrl,\n maxConnections: parseInt(process.env['DATABASE_MAX_CONNECTIONS'] || '20', 10),\n idleTimeoutMillis: parseInt(process.env['DATABASE_IDLE_TIMEOUT'] || '30000', 10),\n connectionTimeoutMillis: parseInt(process.env['DATABASE_CONNECTION_TIMEOUT'] || '10000', 10),\n ...resolvePoolTuningFromEnv(productName),\n enableQueryLogging: isDevelopment,\n slowQueryThreshold: isDevelopment ? 100 : 500,\n ...overrides,\n };\n\n // Transient acquire retry — env-tunable, and unlike the fields above zero is\n // meaningful (DATABASE_ACQUIRE_RETRIES=0 disables the retry entirely).\n const acquireRetriesRaw = process.env['DATABASE_ACQUIRE_RETRIES']?.trim();\n if (acquireRetriesRaw !== undefined && acquireRetriesRaw !== '' && config.acquireRetries === undefined) {\n const parsed = Number.parseInt(acquireRetriesRaw, 10);\n if (Number.isFinite(parsed) && parsed >= 0) {\n config.acquireRetries = parsed;\n }\n }\n const acquireRetryDelay = parsePositiveIntEnv('DATABASE_ACQUIRE_RETRY_DELAY');\n if (acquireRetryDelay !== undefined && config.acquireRetryDelayMillis === undefined) {\n config.acquireRetryDelayMillis = acquireRetryDelay;\n }\n\n return createDatabaseClient(PrismaClientConstructor, config);\n}\n","/**\n * Database Singleton Manager\n *\n * Provides a singleton pattern for database connections across microservices.\n * Services initialize once at startup and access the db instance globally.\n *\n * This eliminates the need for individual db.ts files in each microservice.\n *\n * @module prisma/manager\n * @category Database\n *\n * @example\n * ```typescript\n * // In your service's index.ts (startup)\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { initializeDatabase } from '@burdenoff/be-sdk/prisma';\n *\n * // Initialize once at startup\n * const { db, connect } = initializeDatabase(PrismaClient, 'module-tags');\n * await connect();\n *\n * // In any other file\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n * const db = getDb();\n * await db.client.user.findMany();\n * ```\n */\n\nimport { logger } from '../logger/index.js';\nimport {\n createDatabaseClient,\n createDatabaseClientFromEnv,\n type DatabaseClient,\n type DatabaseClientConfig,\n} from './factory.js';\nimport type { PrismaClientBase, PrismaClientConstructorOptions, DatabaseReturnType } from './client.js';\n\n/**\n * Global database manager state\n */\ninterface DatabaseManagerState {\n initialized: boolean;\n productName: string | null;\n client: DatabaseClient<PrismaClientBase> | null;\n}\n\n/**\n * Singleton state for the database manager\n */\nconst state: DatabaseManagerState = {\n initialized: false,\n productName: null,\n client: null,\n};\n\n/**\n * Initialize the database singleton\n *\n * Call this once at application startup with your service's PrismaClient.\n * After initialization, use `getDb()` to access the database anywhere.\n *\n * @param PrismaClientConstructor - The generated PrismaClient class from your service\n * @param productName - Product name for graph events (e.g., 'module-tags', 'workspaces')\n * @param config - Optional configuration overrides\n * @returns The database client with db, wrapper, connect, disconnect\n *\n * @throws Error if already initialized with a different product\n *\n * @example\n * ```typescript\n * import { PrismaClient } from './generated/prisma/client.js';\n * import { initializeDatabase } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, connect, disconnect } = initializeDatabase(PrismaClient, 'module-tags');\n * await connect();\n * ```\n */\nexport function initializeDatabase<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n productName: string,\n config?: Partial<DatabaseClientConfig>\n): DatabaseClient<T> {\n // Check if already initialized\n if (state.initialized) {\n if (state.productName !== productName) {\n throw new Error(\n `Database already initialized for product \"${state.productName}\". ` +\n `Cannot reinitialize for \"${productName}\".`\n );\n }\n logger.debug('[DatabaseManager] Already initialized, returning existing client', { productName });\n return state.client as DatabaseClient<T>;\n }\n\n // Create the database client using env-based factory\n const client = createDatabaseClientFromEnv(PrismaClientConstructor, productName, config);\n\n // Store in singleton state\n state.initialized = true;\n state.productName = productName;\n state.client = client;\n\n logger.info('[DatabaseManager] Database initialized', { productName });\n\n return client;\n}\n\n/**\n * Initialize the database with explicit configuration\n *\n * Use this when you need full control over database configuration\n * rather than reading from environment variables.\n *\n * @param PrismaClientConstructor - The generated PrismaClient class\n * @param config - Full database configuration\n * @returns The database client\n *\n * @example\n * ```typescript\n * const { db } = initializeDatabaseWithConfig(PrismaClient, {\n * productName: 'module-tags',\n * databaseUrl: 'postgresql://...',\n * maxConnections: 50,\n * enableGraphExtension: false,\n * });\n * ```\n */\nexport function initializeDatabaseWithConfig<T extends PrismaClientBase>(\n PrismaClientConstructor: new (options: PrismaClientConstructorOptions) => T,\n config: DatabaseClientConfig\n): DatabaseClient<T> {\n const { productName } = config;\n\n // Check if already initialized\n if (state.initialized) {\n if (state.productName !== productName) {\n throw new Error(\n `Database already initialized for product \"${state.productName}\". ` +\n `Cannot reinitialize for \"${productName}\".`\n );\n }\n logger.debug('[DatabaseManager] Already initialized, returning existing client', { productName });\n return state.client as DatabaseClient<T>;\n }\n\n // Create the database client\n const client = createDatabaseClient(PrismaClientConstructor, config);\n\n // Store in singleton state\n state.initialized = true;\n state.productName = productName;\n state.client = client;\n\n logger.info('[DatabaseManager] Database initialized with custom config', { productName });\n\n return client;\n}\n\n/**\n * Get the initialized database client\n *\n * Use this anywhere in your application to access the database.\n * Must call `initializeDatabase()` first at application startup.\n *\n * The returned client provides dynamic model access - you can access any\n * model property (e.g., `db.client.user`, `db.client.universalTag`) and\n * TypeScript will allow common Prisma operations (findMany, create, etc.).\n *\n * @returns The extended Prisma client (db) with dynamic model access\n * @throws Error if database not initialized\n *\n * @example\n * ```typescript\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n *\n * const db = getDb();\n * // Dynamic model access works without importing service-specific types\n * const tags = await db.client.universalTag.findMany();\n * const users = await db.client.user.findMany({ where: { active: true } });\n * ```\n */\nexport function getDb<T extends PrismaClientBase = PrismaClientBase>(): DatabaseReturnType<T> {\n if (!state.initialized || !state.client) {\n throw new Error('Database not initialized. Call initializeDatabase() at application startup before using getDb().');\n }\n return state.client.db as unknown as DatabaseReturnType<T>;\n}\n\n/**\n * Get the full database manager\n *\n * Returns the complete database client including wrapper, connect, and disconnect functions.\n * Useful when you need access to connection management utilities.\n *\n * @returns The full database client\n * @throws Error if database not initialized\n *\n * @example\n * ```typescript\n * import { getDatabaseManager } from '@burdenoff/be-sdk/prisma';\n *\n * const { db, wrapper, connect, disconnect } = getDatabaseManager();\n * await connect();\n * ```\n */\nexport function getDatabaseManager<T extends PrismaClientBase = PrismaClientBase>(): DatabaseClient<T> {\n if (!state.initialized || !state.client) {\n throw new Error(\n 'Database not initialized. Call initializeDatabase() at application startup before using getDatabaseManager().'\n );\n }\n return state.client as DatabaseClient<T>;\n}\n\n/**\n * Check if database is initialized\n *\n * @returns True if database has been initialized\n *\n * @example\n * ```typescript\n * if (!isDatabaseInitialized()) {\n * await initializeDatabase(PrismaClient, 'my-service');\n * }\n * ```\n */\nexport function isDatabaseInitialized(): boolean {\n return state.initialized;\n}\n\n/**\n * Get the product name of the initialized database\n *\n * @returns The product name or null if not initialized\n */\nexport function getDatabaseProductName(): string | null {\n return state.productName;\n}\n\n/**\n * Reset the database manager (for testing purposes only)\n *\n * WARNING: This disconnects and resets the database manager.\n * Only use this in test environments for cleanup between tests.\n *\n * @internal\n */\nexport async function resetDatabaseManager(): Promise<void> {\n if (state.client) {\n try {\n await state.client.disconnect();\n } catch (error) {\n logger.warn('[DatabaseManager] Error during disconnect on reset', { error });\n }\n }\n\n state.initialized = false;\n state.productName = null;\n state.client = null;\n\n logger.debug('[DatabaseManager] Database manager reset');\n}\n","/**\n * Prisma Health Check Utilities\n */\n\nimport { logger } from '../logger/index.js';\nimport type { DatabaseHealth } from './types.js';\nimport type { PrismaClientBase } from './client.js';\n\n/**\n * Check database health\n */\nexport async function checkDatabaseHealth<T extends PrismaClientBase>(client: T): Promise<DatabaseHealth> {\n try {\n const start = Date.now();\n await client.$queryRaw`SELECT 1`;\n const latency = Date.now() - start;\n\n return { healthy: true, latency };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error('[Prisma] Health check failed', { error: errorMessage });\n\n return {\n healthy: false,\n error: errorMessage,\n };\n }\n}\n\n/**\n * Test database connection\n */\nexport async function testConnection<T extends PrismaClientBase>(client: T): Promise<boolean> {\n try {\n await client.$queryRaw`SELECT 1`;\n return true;\n } catch (error) {\n logger.error('[Prisma] Connection test failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n return false;\n }\n}\n\n/**\n * Get database version\n */\nexport async function getDatabaseVersion<T extends PrismaClientBase>(client: T): Promise<string | null> {\n try {\n const result = await client.$queryRaw<Array<{ version?: string }>>`SELECT version()`;\n return result[0]?.version ?? null;\n } catch (error) {\n logger.error('[Prisma] Failed to get database version', {\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n}\n\n/**\n * Get database stats\n */\nexport async function getDatabaseStats<T extends PrismaClientBase>(\n client: T\n): Promise<{\n health: DatabaseHealth;\n version: string | null;\n timestamp: Date;\n}> {\n const [health, version] = await Promise.all([checkDatabaseHealth(client), getDatabaseVersion(client)]);\n\n return {\n health,\n version,\n timestamp: new Date(),\n };\n}\n","/**\n * Prisma Field Extraction Utilities\n *\n * Provides utilities for extracting model fields from Prisma schema.\n * In Prisma 7, DMMF is not available at runtime, so this module provides\n * build-time field extraction through a generator.\n *\n * @module prisma/fields\n */\n\nimport { createRequire } from 'node:module';\nimport { logger } from '../logger/index.js';\n\nconst requireFn = createRequire(import.meta.url);\n\n/**\n * Field extraction options\n */\nexport interface FieldExtractionOptions {\n /** Fields to exclude from extraction */\n excludeFields?: string[];\n /** Whether to include relation fields */\n includeRelations?: boolean;\n /** Custom filter function */\n customFilter?: (field: { name: string; type: string; isRelation: boolean }) => boolean;\n}\n\n/**\n * Field extraction result\n */\nexport interface FieldExtractionResult {\n /** Extracted field names */\n fields: string[];\n /** Metadata about the extraction */\n metadata: {\n /** Total number of fields found */\n totalFields: number;\n /** Number of fields excluded */\n excludedCount: number;\n /** Names of excluded fields */\n excludedFields: string[];\n /** Number of relation fields */\n relationFields: number;\n };\n}\n\n/**\n * Model fields mapping\n * This will be generated at build time by the Prisma generator\n */\nexport type ModelFieldsMap = Record<\n string,\n {\n fields: string[];\n relations: string[];\n }\n>;\n\n/**\n * Import generated fields from the consuming package\n * This function should be used by backends to load their generated fields\n */\nexport function loadGeneratedFields(generatedFieldsPath: string): ModelFieldsMap {\n try {\n // Dynamic import of generated fields using createRequire\n const generated = requireFn(generatedFieldsPath) as { default: ModelFieldsMap };\n return generated.default || generated;\n } catch (error) {\n logger.error('[Prisma] Failed to load generated fields', {\n error: error instanceof Error ? error.message : String(error),\n path: generatedFieldsPath,\n });\n throw new Error(`Failed to load generated fields from ${generatedFieldsPath}`);\n }\n}\n\n/**\n * Extract fields from generated model fields with options\n */\nexport function extractFieldsFromModel(\n modelName: string,\n modelFieldsMap: ModelFieldsMap,\n options: FieldExtractionOptions = {}\n): FieldExtractionResult {\n const modelFields = modelFieldsMap[modelName];\n\n if (!modelFields) {\n throw new Error(\n `Model \"${modelName}\" not found in generated fields. ` +\n `Available models: ${Object.keys(modelFieldsMap).join(', ')}`\n );\n }\n\n const { excludeFields = [], includeRelations = false, customFilter } = options;\n\n // Start with scalar fields\n let fields = [...modelFields.fields];\n\n // Add relations if requested\n if (includeRelations) {\n fields = [...fields, ...modelFields.relations];\n }\n\n // Track excluded fields\n const excluded: string[] = [];\n\n // Apply exclusions\n if (excludeFields.length > 0) {\n fields = fields.filter((field) => {\n if (excludeFields.includes(field)) {\n excluded.push(field);\n return false;\n }\n return true;\n });\n }\n\n // Apply custom filter\n if (customFilter) {\n fields = fields.filter((fieldName) => {\n const isRelation = modelFields.relations.includes(fieldName);\n const shouldInclude = customFilter({\n name: fieldName,\n type: 'unknown', // Type information not available without full DMMF\n isRelation,\n });\n\n if (!shouldInclude) {\n excluded.push(fieldName);\n }\n\n return shouldInclude;\n });\n }\n\n return {\n fields,\n metadata: {\n totalFields: modelFields.fields.length + modelFields.relations.length,\n excludedCount: excluded.length,\n excludedFields: excluded,\n relationFields: modelFields.relations.length,\n },\n };\n}\n\n/**\n * Get all field names for a model (without options)\n */\nexport function getModelFields(modelName: string, modelFieldsMap: ModelFieldsMap, includeRelations = false): string[] {\n const result = extractFieldsFromModel(modelName, modelFieldsMap, { includeRelations });\n return result.fields;\n}\n\n/**\n * Check if a model exists in the generated fields\n */\nexport function hasModel(modelName: string, modelFieldsMap: ModelFieldsMap): boolean {\n return modelName in modelFieldsMap;\n}\n\n/**\n * Get all available model names\n */\nexport function getAllModelNames(modelFieldsMap: ModelFieldsMap): string[] {\n return Object.keys(modelFieldsMap);\n}\n","/**\n * Prisma Context Filtering Utilities\n *\n * Utilities for handling operation context in queries, mutations, and filtering.\n * Context JSON enables multi-dimensional data isolation across workspaces, users, projects, etc.\n *\n * @module prisma/context\n * @category Database\n */\n\nimport { isSameProductSlug, productSlugVariants } from '../product-alias/index.js';\n\n/**\n * Context filter input for querying entities by context\n */\nexport interface ContextFilterInput {\n workspaceId?: string | null;\n userId?: string | null;\n projectId?: string | null;\n appId?: string | null;\n /** Product identifier (e.g. \"vibecontrols\", \"workspaces\"). Stamped on cross-product\n * records so admin filters can scope by originating product. */\n productId?: string | null;\n /** Organization identifier within the tenant. */\n organizationId?: string | null;\n}\n\n/**\n * Operation context for create/update operations\n */\nexport interface OperationContext extends ContextFilterInput {\n custom?: Record<string, unknown> | null;\n}\n\n/**\n * Prisma JSON filter type (simplified for context filtering)\n * This type is designed to be compatible with Prisma's JsonNullableFilter\n * Uses Record<string, unknown> for maximum compatibility with various Prisma versions\n */\nexport type PrismaJsonFilter = Record<string, unknown>;\n\n/**\n * One entry of {@link buildContextWhereConditions}: a JSON-path predicate on `context`,\n * or an `OR` of them (used for a renamed product's slug twins).\n */\nexport type ContextWhereCondition = { context: PrismaJsonFilter } | { OR: Array<{ context: PrismaJsonFilter }> };\n\n/**\n * JSON value type for Prisma (includes null for reading from DB)\n */\nexport type JsonValue = string | number | boolean | null | { [key: string]: JsonValue } | JsonValue[];\n\n/**\n * Input JSON value type for Prisma (excludes null for writing to DB)\n * Compatible with Prisma's InputJsonValue type\n */\nexport type InputJsonValue = string | number | boolean | { [key: string]: InputJsonValue } | InputJsonValue[];\n\n/**\n * Build Prisma where condition for context filtering.\n * Uses PostgreSQL JSONB containment operators for efficient queries.\n *\n * @param contextFilter - The context filter input\n * @returns Prisma where clause for context field, or undefined if no filter provided\n *\n * @example\n * ```typescript\n * const contextWhere = buildContextWhereClause({\n * workspaceId: '123',\n * projectId: '456'\n * });\n * // Returns: { path: ['workspaceId'], equals: '123' }\n * ```\n */\nexport function buildContextWhereClause(\n contextFilter: ContextFilterInput | null | undefined\n): PrismaJsonFilter | undefined {\n if (!contextFilter) {\n return undefined;\n }\n\n // Build array of path conditions for each non-null field\n const conditions: PrismaJsonFilter[] = [];\n\n if (contextFilter.workspaceId != null) {\n conditions.push({\n path: ['workspaceId'],\n equals: contextFilter.workspaceId,\n });\n }\n\n if (contextFilter.userId != null) {\n conditions.push({\n path: ['userId'],\n equals: contextFilter.userId,\n });\n }\n\n if (contextFilter.projectId != null) {\n conditions.push({\n path: ['projectId'],\n equals: contextFilter.projectId,\n });\n }\n\n if (contextFilter.appId != null) {\n conditions.push({\n path: ['appId'],\n equals: contextFilter.appId,\n });\n }\n\n if (contextFilter.productId != null) {\n conditions.push({\n path: ['productId'],\n equals: contextFilter.productId,\n });\n }\n\n if (contextFilter.organizationId != null) {\n conditions.push({\n path: ['organizationId'],\n equals: contextFilter.organizationId,\n });\n }\n\n // If no conditions, return undefined\n if (conditions.length === 0) {\n return undefined;\n }\n\n // If single condition, return it directly\n if (conditions.length === 1) {\n return conditions[0];\n }\n\n // For multiple conditions, return the first one\n // Caller should use buildContextWhereConditions for multiple AND conditions\n return conditions[0];\n}\n\n/**\n * Build context where conditions as an array for use in AND clause.\n * This is useful when you need to filter by multiple context fields.\n *\n * @param contextFilter - The context filter input\n * @returns Array of Prisma where conditions, each targeting the context field\n *\n * @example\n * ```typescript\n * const conditions = buildContextWhereConditions({\n * workspaceId: '123',\n * projectId: '456'\n * });\n * // Use in Prisma query:\n * prisma.entity.findMany({\n * where: { AND: conditions }\n * });\n * ```\n */\nexport function buildContextWhereConditions(\n contextFilter: ContextFilterInput | null | undefined\n): ContextWhereCondition[] {\n if (!contextFilter) {\n return [];\n }\n\n const conditions: ContextWhereCondition[] = [];\n\n if (contextFilter.workspaceId != null) {\n conditions.push({\n context: {\n path: ['workspaceId'],\n equals: contextFilter.workspaceId,\n },\n });\n }\n\n if (contextFilter.userId != null) {\n conditions.push({\n context: {\n path: ['userId'],\n equals: contextFilter.userId,\n },\n });\n }\n\n if (contextFilter.projectId != null) {\n conditions.push({\n context: {\n path: ['projectId'],\n equals: contextFilter.projectId,\n },\n });\n }\n\n if (contextFilter.appId != null) {\n conditions.push({\n context: {\n path: ['appId'],\n equals: contextFilter.appId,\n },\n });\n }\n\n if (contextFilter.productId != null) {\n // A renamed product (botlit → botmanor) matches rows stored under either slug while\n // they are migrated; every other product keeps the exact single-slug predicate.\n const slugs = productSlugVariants(contextFilter.productId);\n if (slugs.length > 1) {\n conditions.push({\n OR: slugs.map((slug) => ({ context: { path: ['productId'], equals: slug } })),\n });\n } else {\n conditions.push({\n context: {\n path: ['productId'],\n equals: contextFilter.productId,\n },\n });\n }\n }\n\n if (contextFilter.organizationId != null) {\n conditions.push({\n context: {\n path: ['organizationId'],\n equals: contextFilter.organizationId,\n },\n });\n }\n\n return conditions;\n}\n\n/**\n * Convert context input to Prisma JSON format for create/update operations.\n *\n * @param contextInput - The context input\n * @returns JSON value for the context field, or undefined if empty\n *\n * @example\n * ```typescript\n * const contextJson = toContextJson({\n * workspaceId: '123',\n * userId: '456'\n * });\n * // Use in Prisma create:\n * prisma.entity.create({\n * data: { context: contextJson }\n * });\n * ```\n */\nexport function toContextJson(contextInput: OperationContext | null | undefined): InputJsonValue | undefined {\n if (!contextInput) {\n return undefined;\n }\n\n // Remove null values and build clean context object\n const context: Record<string, InputJsonValue> = {};\n\n if (contextInput.workspaceId != null) {\n context['workspaceId'] = contextInput.workspaceId;\n }\n if (contextInput.userId != null) {\n context['userId'] = contextInput.userId;\n }\n if (contextInput.projectId != null) {\n context['projectId'] = contextInput.projectId;\n }\n if (contextInput.appId != null) {\n context['appId'] = contextInput.appId;\n }\n if (contextInput.productId != null) {\n context['productId'] = contextInput.productId;\n }\n if (contextInput.organizationId != null) {\n context['organizationId'] = contextInput.organizationId;\n }\n if (contextInput.custom != null) {\n context['custom'] = contextInput.custom as InputJsonValue;\n }\n\n // Return undefined if no fields set\n if (Object.keys(context).length === 0) {\n return undefined;\n }\n\n return context;\n}\n\n/**\n * Filter out null values from an object for Prisma compatibility\n */\nfunction filterNullValues(obj: Record<string, unknown>): Record<string, InputJsonValue> {\n const filtered: Record<string, InputJsonValue> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== null) {\n filtered[key] = value as InputJsonValue;\n }\n }\n return filtered;\n}\n\n/**\n * Merge a single field into the merged context object\n */\nfunction mergeContextField(\n merged: Record<string, InputJsonValue>,\n fieldName: string,\n fieldValue: string | Record<string, unknown> | null | undefined\n): void {\n if (fieldValue === undefined) {\n return; // Don't touch this field\n }\n\n if (fieldValue === null) {\n delete merged[fieldName]; // Explicitly remove\n } else {\n merged[fieldName] = fieldValue as InputJsonValue; // Set new value\n }\n}\n\n/**\n * Merge existing context with new context input.\n * New values override existing ones, but undefined values are preserved from existing.\n *\n * @param existingContext - The existing context JSON from database\n * @param newContext - The new context input\n * @returns Merged context as InputJsonValue (suitable for Prisma writes)\n *\n * @example\n * ```typescript\n * const merged = mergeContext(\n * { workspaceId: '123', userId: 'old' },\n * { userId: 'new', projectId: '456' }\n * );\n * // Result: { workspaceId: '123', userId: 'new', projectId: '456' }\n * ```\n */\nexport function mergeContext(\n existingContext: JsonValue | null | undefined,\n newContext: OperationContext | null | undefined\n): InputJsonValue | undefined {\n // If no new context, return existing (excluding null values)\n if (!newContext) {\n if (!existingContext) {\n return undefined;\n }\n // Filter out null values from existing context for Prisma compatibility\n if (typeof existingContext === 'object' && !Array.isArray(existingContext)) {\n const filtered = filterNullValues(existingContext);\n return Object.keys(filtered).length > 0 ? filtered : undefined;\n }\n return existingContext as InputJsonValue;\n }\n\n // If no existing context, convert new to JSON\n if (!existingContext || typeof existingContext !== 'object' || Array.isArray(existingContext)) {\n return toContextJson(newContext);\n }\n\n // Merge existing with new\n const merged = filterNullValues(existingContext);\n\n // Merge each field from new context\n mergeContextField(merged, 'workspaceId', newContext.workspaceId);\n mergeContextField(merged, 'userId', newContext.userId);\n mergeContextField(merged, 'projectId', newContext.projectId);\n mergeContextField(merged, 'appId', newContext.appId);\n mergeContextField(merged, 'productId', newContext.productId);\n mergeContextField(merged, 'organizationId', newContext.organizationId);\n mergeContextField(merged, 'custom', newContext.custom);\n\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\n/**\n * Parse context JSON from database to OperationContext interface.\n *\n * @param contextJson - The context JSON from database\n * @returns Parsed OperationContext or null\n *\n * @example\n * ```typescript\n * const context = parseContext(entity.context);\n * if (context?.workspaceId) {\n * // Use workspace-specific logic\n * }\n * ```\n */\nexport function parseContext(contextJson: JsonValue | null | undefined): OperationContext | null {\n if (!contextJson || typeof contextJson !== 'object' || Array.isArray(contextJson)) {\n return null;\n }\n\n const ctx = contextJson as Record<string, unknown>;\n\n return {\n workspaceId: typeof ctx['workspaceId'] === 'string' ? ctx['workspaceId'] : null,\n userId: typeof ctx['userId'] === 'string' ? ctx['userId'] : null,\n projectId: typeof ctx['projectId'] === 'string' ? ctx['projectId'] : null,\n appId: typeof ctx['appId'] === 'string' ? ctx['appId'] : null,\n productId: typeof ctx['productId'] === 'string' ? ctx['productId'] : null,\n organizationId: typeof ctx['organizationId'] === 'string' ? ctx['organizationId'] : null,\n custom: typeof ctx['custom'] === 'object' ? (ctx['custom'] as Record<string, unknown>) : null,\n };\n}\n\n/**\n * Check if context matches filter criteria\n *\n * @param context - The context to check\n * @param filter - The filter criteria\n * @returns True if context matches all filter criteria\n */\nexport function contextMatches(context: OperationContext | null | undefined, filter: ContextFilterInput): boolean {\n if (!context) {\n return false;\n }\n\n if (filter.workspaceId != null && context.workspaceId !== filter.workspaceId) {\n return false;\n }\n if (filter.userId != null && context.userId !== filter.userId) {\n return false;\n }\n if (filter.projectId != null && context.projectId !== filter.projectId) {\n return false;\n }\n if (filter.appId != null && context.appId !== filter.appId) {\n return false;\n }\n // Renamed products (botlit → botmanor) match under either slug while rows are migrated.\n if (filter.productId != null && !isSameProductSlug(context.productId, filter.productId)) {\n return false;\n }\n if (filter.organizationId != null && context.organizationId !== filter.organizationId) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Create a default context from SDK context\n *\n * @param sdkContext - The SDK context (from AsyncLocalStorage)\n * @returns Operation context with workspace and user info\n */\nexport function createContextFromSDK(sdkContext: {\n workspaceId?: string;\n userId?: string;\n projectId?: string;\n appId?: string;\n productId?: string;\n organizationId?: string;\n}): OperationContext {\n return {\n workspaceId: sdkContext.workspaceId ?? null,\n userId: sdkContext.userId ?? null,\n projectId: sdkContext.projectId ?? null,\n appId: sdkContext.appId ?? null,\n productId: sdkContext.productId ?? null,\n organizationId: sdkContext.organizationId ?? null,\n };\n}\n","/**\n * Prisma Module for Burdenoff Backend SDK\n *\n * Provides Prisma 7 utilities including:\n * - Singleton database manager for microservices\n * - Unified database client factory with graph extension\n * - Prisma client configuration with PostgreSQL adapter\n * - Connection pooling and management\n * - Health checks and monitoring\n * - Graceful shutdown handling\n * - Field extraction utilities for graph sync\n * - Context filtering utilities for multi-tenant queries\n * - Workspace extension for automatic workspaceId injection\n *\n * @module prisma\n * @category Database\n */\n\nexport * from './manager.js';\nexport * from './factory.js';\nexport * from './client.js';\nexport type * from './types.js';\nexport * from './health.js';\nexport * from './fields.js';\nexport * from './context.js';\nexport * from './workspace-extension.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8GA,SAAS,iCAAiC,aAA8B;CACtE,MAAM,WAAW,QAAQ,IAAI;CAC7B,IAAI,aAAa,QAAQ,OAAO;CAChC,IAAI,aAAa,SAAS,OAAO;CAEjC,MAAM,QAAQ,QAAQ,IAAI,kBAAkB,EAAE,YAAY;CAC1D,IAAI,UAAU,UAAU,OAAO;CAC/B,IAAI,UAAU,UAAU,OAAO;CAE/B,MAAM,OAAO,YAAY,YAAY;CACrC,IAAI,KAAK,WAAW,SAAS,KAAK,KAAK,WAAW,SAAS,GAAG,OAAO;CACrE,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,qBACd,yBACA,QACmB;CACnB,MAAM,EACJ,aACA,uBAAuB,QAAQ,IAAI,gCAAgC,SACnE,mBACA,2BAA2B,iCAAiC,WAAW,GACvE,0BACA,2BAA2B,MAC3B,GAAG,iBACD;CAOJ,MAAM,2BAA+C;EACnD,GAAG;EACH,iBAAiB,aAAa,mBAAmB,OAAO;CAC1D;CAIA,6BAA6B,WAAW;CAGxC,MAAM,UAAU,mBAAmB,yBAAyB,wBAAwB;CAGpF,MAAM,aAAa,QAAQ,UAAU;CAWrC,IAAI;CAGJ,IAAI,sBAAsB;EAGxB,MAAM,cAAqC;GACzC,SAAS;GACT;GACA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AAW,IAAI,WAAW;EACzD,WAAW,OAAO,IAAI,iBAAiB,WAAW,IAAI,eAAe;EACrE,gBAAgB,OAAO,IAAI,sBAAsB,WAAW,IAAI,oBAAoB;EACpF,QAAQ,OAAO,IAAI,cAAc,WAAY,IAAI,YAAwC;CAC3F;AACF;;;;;;;;AASA,SAAgB,eAAe,SAA8C,QAAqC;CAChH,IAAI,CAAC,SACH,OAAO;CAGT,IAAI,OAAO,eAAe,QAAQ,QAAQ,gBAAgB,OAAO,aAC/D,OAAO;CAET,IAAI,OAAO,UAAU,QAAQ,QAAQ,WAAW,OAAO,QACrD,OAAO;CAET,IAAI,OAAO,aAAa,QAAQ,QAAQ,cAAc,OAAO,WAC3D,OAAO;CAET,IAAI,OAAO,SAAS,QAAQ,QAAQ,UAAU,OAAO,OACnD,OAAO;CAGT,IAAI,OAAO,aAAa,QAAQ,CAAC,kBAAkB,QAAQ,WAAW,OAAO,SAAS,GACpF,OAAO;CAET,IAAI,OAAO,kBAAkB,QAAQ,QAAQ,mBAAmB,OAAO,gBACrE,OAAO;CAGT,OAAO;AACT;;;;;;;AAQA,SAAgB,qBAAqB,YAOhB;CACnB,OAAO;EACL,aAAa,WAAW,eAAe;EACvC,QAAQ,WAAW,UAAU;EAC7B,WAAW,WAAW,aAAa;EACnC,OAAO,WAAW,SAAS;EAC3B,WAAW,WAAW,aAAa;EACnC,gBAAgB,WAAW,kBAAkB;CAC/C;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-ad2WFvuA.js";
2
2
  import { a as logger } from "../logger-B6rCpb7D.js";
3
- import { c as ACTOR_ORIGIN_HEADER, d as ASSISTANT_SESSION_ID_HEADER, f as parseAssistantSessionHeaders, l as AI_ASSISTANT_ACTOR_ORIGIN, m as toAssistantSessionAttribution, o as trackOperation, p as readAssistantSessionAttribution, u as ASSISTANT_CORRELATION_ID_HEADER } from "../stub-DZ332ZHG.js";
4
- import { w as withWorkspaceContext, x as setWorkspaceContext } from "../workspace-extension-ByopOwtK.js";
3
+ import { c as ACTOR_ORIGIN_HEADER, d as ASSISTANT_SESSION_ID_HEADER, f as parseAssistantSessionHeaders, l as AI_ASSISTANT_ACTOR_ORIGIN, m as toAssistantSessionAttribution, o as trackOperation, p as readAssistantSessionAttribution, u as ASSISTANT_CORRELATION_ID_HEADER } from "../stub-DNkzpQvR.js";
4
+ import { w as withWorkspaceContext, x as setWorkspaceContext } from "../workspace-extension-BcMPoGWr.js";
5
5
  import { l as I18n } from "../i18n-BBMYFd0P.js";
6
6
  import { l as getMetricsRegistry } from "../metrics-collector-DXQrMUle.js";
7
7
  import { t as getWorkspaceQuotaRegistry } from "../metrics-CQaHT12m.js";
@@ -1,6 +1,6 @@
1
1
  import { a as logger } from "./logger-B6rCpb7D.js";
2
2
  import { n as markExplicitActivity } from "./explicit-activity-scope-DikJ7NAE.js";
3
- import { c as getScopedWorkspaceContext, l as getWorkspaceContext } from "./workspace-extension-ByopOwtK.js";
3
+ import { c as getScopedWorkspaceContext, l as getWorkspaceContext } from "./workspace-extension-BcMPoGWr.js";
4
4
  import { randomUUID } from "node:crypto";
5
5
 
6
6
  // src/activity/assistant-session.ts
@@ -574,4 +574,4 @@ const UNIFIED_TRACKER_CONSTANTS = {
574
574
  };
575
575
 
576
576
  export { resolveAssistantSession as a, ACTOR_ORIGIN_HEADER as c, ASSISTANT_SESSION_ID_HEADER as d, parseAssistantSessionHeaders as f, isTrackedActorType as i, AI_ASSISTANT_ACTOR_ORIGIN as l, toAssistantSessionAttribution as m, UnifiedTrackerStub as n, trackOperation as o, readAssistantSessionAttribution as p, createProductTracker as r, trackerStub as s, UNIFIED_TRACKER_CONSTANTS as t, ASSISTANT_CORRELATION_ID_HEADER as u };
577
- //# sourceMappingURL=stub-DZ332ZHG.js.map
577
+ //# sourceMappingURL=stub-DNkzpQvR.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"stub-DZ332ZHG.js","names":[],"sources":["../src/activity/assistant-session.ts","../src/tracker/stub.ts"],"sourcesContent":["/**\n * Assistant-session attribution (BOFF-9649)\n *\n * When an AI assistant session runs a GraphQL mutation for its owner, the\n * assistant session relay (wspace-sandbox-svc) forwards it to a public gateway\n * as the owner, with a signed assistant-session marker. The gateway verifies\n * that marker against the owner's verified token, strips any copy a client\n * sent, and passes the result to subgraphs as three headers:\n *\n * x-actor-origin: ai_assistant\n * x-assistant-session-id: <the relay session id (the assistant sandbox id)>\n * x-assistant-correlation-id: <the proposal / idempotency key, when there is one>\n *\n * A service never verifies these itself. `buildContext` reads them only when it\n * already trusts the gateway's actor headers, exposes them as\n * `context.assistantSession`, and binds them to the operation's workspace\n * context so `trackOperation` can stamp every activity row written while the\n * operation runs, without each service re-implementing audit.\n *\n * Values outside the vocabulary or the id pattern are dropped, never coerced:\n * a wrong attribution is worse than none.\n */\n\n/** The only actor origin the platform records today. */\nexport const AI_ASSISTANT_ACTOR_ORIGIN = 'ai_assistant';\n\nexport type ActorOrigin = typeof AI_ASSISTANT_ACTOR_ORIGIN;\n\n/** Gateway-to-subgraph headers. Clients cannot set them: the public gateways strip them. */\nexport const ACTOR_ORIGIN_HEADER = 'x-actor-origin';\nexport const ASSISTANT_SESSION_ID_HEADER = 'x-assistant-session-id';\nexport const ASSISTANT_CORRELATION_ID_HEADER = 'x-assistant-correlation-id';\n\n/** Session ids (UUIDs, cuid-style ids) and proposal / idempotency keys. */\nconst ATTRIBUTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** The assistant session an operation ran under. */\nexport interface AssistantSessionAttribution {\n actorOrigin: ActorOrigin;\n /** The relay session id: the assistant sandbox that ran the mutation. */\n assistantSessionId: string;\n /** The proposal / idempotency key the mutation ran under, when it had one. */\n assistantCorrelationId?: string;\n}\n\nfunction attributionId(value: unknown): string | undefined {\n return typeof value === 'string' && ATTRIBUTION_ID_PATTERN.test(value) ? value : undefined;\n}\n\n/**\n * Build an attribution from raw values. Undefined unless the origin is\n * `ai_assistant` and the session id is well formed; a malformed correlation id\n * is dropped on its own.\n */\nexport function toAssistantSessionAttribution(\n actorOrigin: unknown,\n assistantSessionId: unknown,\n assistantCorrelationId?: unknown\n): AssistantSessionAttribution | undefined {\n if (actorOrigin !== AI_ASSISTANT_ACTOR_ORIGIN) return undefined;\n const sessionId = attributionId(assistantSessionId);\n if (!sessionId) return undefined;\n const correlationId = attributionId(assistantCorrelationId);\n return {\n actorOrigin: AI_ASSISTANT_ACTOR_ORIGIN,\n assistantSessionId: sessionId,\n ...(correlationId ? { assistantCorrelationId: correlationId } : {}),\n };\n}\n\n/**\n * Read the gateway's assistant-session headers. The caller decides whether the\n * request's gateway headers are trusted at all; this only parses them.\n */\nexport function parseAssistantSessionHeaders(\n getHeader: (name: string) => string | null | undefined\n): AssistantSessionAttribution | undefined {\n return toAssistantSessionAttribution(\n getHeader(ACTOR_ORIGIN_HEADER),\n getHeader(ASSISTANT_SESSION_ID_HEADER),\n getHeader(ASSISTANT_CORRELATION_ID_HEADER)\n );\n}\n\n/** Re-validate an attribution-shaped value (from a request context or caller options). */\nexport function readAssistantSessionAttribution(value: unknown): AssistantSessionAttribution | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Record<string, unknown>;\n return toAssistantSessionAttribution(\n record['actorOrigin'],\n record['assistantSessionId'],\n record['assistantCorrelationId']\n );\n}\n","/**\n * Unified Tracking — Auto-Promoting Implementation\n *\n * Automatically promotes from stub to real tracking when gateway URLs are configured.\n * When WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL is set, this module will:\n * - Log activity events via GraphQL to the activity service\n * - Track usage via GraphQL to the usage service (if usage options provided)\n * - RBAC checks are NOT performed here (handled by gateway @rbac directives)\n *\n * When no gateway URL is configured, falls back to debug-level logging (stub mode).\n *\n * This is a backward-compatible drop-in replacement for the original stub. All 1,100+\n * existing call sites continue to work without modification.\n *\n * @module tracker/stub\n * @category Tracking\n */\nimport { randomUUID } from 'node:crypto';\n\nimport { logger } from '../logger/index.js';\nimport { markExplicitActivity } from '../activity/explicit-activity-scope.js';\nimport { readAssistantSessionAttribution, type AssistantSessionAttribution } from '../activity/assistant-session.js';\nimport { getScopedWorkspaceContext, getWorkspaceContext } from '../prisma/workspace-extension.js';\n\n/**\n * Tracking event interface\n */\nexport interface TrackingEvent {\n eventType: string;\n entityType: string;\n entityId: string;\n userId?: string;\n workspaceId?: string;\n metadata?: Record<string, unknown>;\n timestamp?: Date;\n}\n\n/**\n * RBAC check options\n */\nexport interface RbacCheckOptions {\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n skipRbacCheck?: boolean;\n options?: {\n allowOwnerAccess?: boolean;\n allowWorkspaceAdmin?: boolean;\n scope?: string;\n };\n}\n\n/**\n * Usage tracking options\n */\nexport interface UsageTrackingOptions {\n billingAccountId?: string;\n addUsage?: boolean;\n description?: string;\n tags?: Record<string, unknown>;\n quotaName?: string;\n value?: number;\n}\n\n/**\n * Activity tracking options\n */\nexport interface ActivityTrackingOptions {\n activityType?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n workspaceId?: string;\n teamId?: string;\n groupId?: string;\n projectId?: string;\n targetUserId?: string;\n resourceType?: string;\n resourceId?: string;\n enabled?: boolean;\n /**\n * Idempotency key forwarded to the activity owner's `RecordActivityInput.dedupeKey`.\n * When omitted, a unique key is generated per tracked operation so that delivery retries of the\n * SAME operation converge to exactly one activity row. Supply a stable key only when the caller\n * itself may replay the same logical event (backfill/import).\n */\n dedupeKey?: string;\n}\n\n/**\n * Kind of actor behind a tracked operation — the gateway `x-actor-type` vocabulary.\n *\n * An AI agent acting through a product service is an `app` actor; recording it lets the\n * activity owner tell agent actions apart from human ones (BOFF-9684).\n */\nexport type TrackedActorType = 'user' | 'app' | 'service' | 'super_admin';\n\nconst TRACKED_ACTOR_TYPES: ReadonlySet<string> = new Set<TrackedActorType>(['user', 'app', 'service', 'super_admin']);\n\nexport function isTrackedActorType(value: unknown): value is TrackedActorType {\n return typeof value === 'string' && TRACKED_ACTOR_TYPES.has(value);\n}\n\n/**\n * Unified tracking options\n */\nexport interface UnifiedTrackingOptions {\n operationName?: string;\n userId?: string;\n /**\n * Kind of actor `userId` identifies. When omitted it is taken from `context` (`actor.type` or\n * `actorType`) or, with no `context`, from the ambient be-sdk workspace context; a value outside\n * the vocabulary is dropped rather than sent. The activity owner honours it because the tracker\n * calls it as a relaying `service`.\n */\n actorType?: TrackedActorType;\n /**\n * The user on whose behalf `userId` acted — for an AI-agent action, the human who started the\n * run. When omitted it is taken from `context.onBehalfOf`; the activity owner otherwise records\n * the actor itself.\n */\n onBehalfOf?: string;\n /**\n * The AI assistant session the operation ran under (BOFF-9649). When omitted it is taken from\n * `context.assistantSession` or, failing that, from the operation's own async scope (never from\n * another request's). Sent to global-activity-svc as `actorOrigin` / `assistantSessionId` /\n * `assistantCorrelationId`.\n */\n assistantSession?: AssistantSessionAttribution;\n context?: unknown;\n rbacCheck?: RbacCheckOptions;\n activityOptions?: ActivityTrackingOptions;\n usageOptions?: UsageTrackingOptions & { enabled?: boolean };\n success?: boolean;\n errorMessage?: string;\n productId?: string;\n // Legacy properties for backward compatibility (can be at top level or in nested objects)\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n tenantId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Gateway URL resolution — cached at module level for performance\n// ---------------------------------------------------------------------------\n\nlet _gatewayUrl: string | undefined;\nlet _gatewayLayer: ActivityLayer | undefined;\nlet _gatewayUrlResolved = false;\n\n/**\n * Which activity subgraph the resolved gateway fronts.\n *\n * The two canonical activity owners accept DIFFERENT `RecordActivityInput` shapes, so the\n * payload must be built per layer:\n * - `wspace` → wspace-activity-svc: requires `action`; carries workspace-scoped fields\n * (workspaceId/teamId/targetUserId/productId/success).\n * - `global` → global-activity-svc: requires `action` AND `resource`; carries tenant-scoped\n * fields (tenantId/actorId/ipAddress/userAgent).\n * Sending one layer's shape to the other fails GraphQL validation.\n */\nexport type ActivityLayer = 'wspace' | 'global';\n\n/**\n * The layer the running service belongs to, when its environment says so: `SERVICE_LAYER`, then a\n * `global-` / `wspace-` `SERVICE_NAME` prefix (the same rule the RBAC directive and the Temporal\n * client use). Undefined when neither says.\n */\nfunction declaredServiceLayer(): ActivityLayer | undefined {\n const layer = process.env['SERVICE_LAYER'];\n if (layer === 'global' || layer === 'wspace') return layer;\n const name = process.env['SERVICE_NAME'] ?? '';\n if (name.startsWith('global-')) return 'global';\n if (name.startsWith('wspace-')) return 'wspace';\n return undefined;\n}\n\n/**\n * Resolve the internal gateway URL from environment.\n *\n * Activity belongs to the service's OWN layer: workspace services record in wspace-activity-svc\n * through WSPACE_INT_GATEWAY_URL, global services in global-activity-svc through\n * GLOBAL_INT_GATEWAY_URL. Global services also hold WSPACE_INT_GATEWAY_URL for cross-layer\n * calls, so the URL that happens to be set is not a layer signal: the declared layer\n * (`SERVICE_LAYER` / `SERVICE_NAME`) decides, and only an undeclared service falls back to\n * \"workspace URL first\" (BOFF-9649 — every global service was sending its audit rows to the\n * workspace activity owner, which rejected them). Undefined (stub mode) when no URL is set.\n */\nfunction getGatewayUrl(): string | undefined {\n if (!_gatewayUrlResolved) {\n const wspaceUrl = process.env['WSPACE_INT_GATEWAY_URL'];\n const globalUrl = process.env['GLOBAL_INT_GATEWAY_URL'];\n const declared = declaredServiceLayer();\n\n // A declared global service uses its own owner; anything else keeps \"workspace URL first\".\n const useGlobal = Boolean(globalUrl) && (declared === 'global' || !wspaceUrl);\n if (useGlobal) {\n _gatewayUrl = globalUrl;\n _gatewayLayer = 'global';\n } else if (wspaceUrl) {\n _gatewayUrl = wspaceUrl;\n _gatewayLayer = 'wspace';\n } else {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n }\n if (declared && _gatewayLayer && declared !== _gatewayLayer) {\n logger.warn(\n `[trackOperation] ${declared} service has no ${declared === 'global' ? 'GLOBAL' : 'WSPACE'}_INT_GATEWAY_URL; activity goes to the ${_gatewayLayer} activity owner instead`\n );\n }\n _gatewayUrlResolved = true;\n\n if (_gatewayUrl) {\n logger.info(`[trackOperation] Real tracking enabled via ${_gatewayLayer} gateway: ${_gatewayUrl}`);\n } else {\n logger.debug('[trackOperation] No gateway URL configured — running in stub mode');\n }\n }\n return _gatewayUrl;\n}\n\n/**\n * Resolve which activity layer the configured gateway fronts.\n * Always call `getGatewayUrl()` first — it performs the resolution.\n */\nfunction getGatewayLayer(): ActivityLayer {\n // Default to 'wspace': the overwhelming majority of services are workspace-layer, and a wspace\n // payload omits only optional global fields, so a mis-detection degrades rather than fails.\n return _gatewayLayer ?? 'wspace';\n}\n\n/**\n * Reset the cached gateway resolution. Test-only seam — module-level caching would otherwise make\n * per-layer behaviour untestable within a single process.\n */\nexport function __resetGatewayCacheForTests(): void {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n _gatewayUrlResolved = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fire-and-forget GraphQL helper\n// ---------------------------------------------------------------------------\n\nconst LOG_ACTIVITY_MUTATION = /* GraphQL */ `\n mutation RecordActivity($input: RecordActivityInput!) {\n recordActivity(input: $input) {\n id\n }\n }\n`;\n\n/**\n * Derive the `resource` value required by global-activity-svc.\n *\n * Prefers an explicit resourceType; otherwise falls back to the leading dotted segment of the\n * operation name (`auth.session.revoke` → `auth`), which matches the platform's\n * `<domain>.<resource>.<verb>` activity taxonomy. Never returns empty — `resource` is non-nullable\n * on global-activity-svc and an empty string would be silently useless in the audit trail.\n */\nfunction deriveResource(options: UnifiedTrackingOptions): string {\n const explicit = options.activityOptions?.resourceType ?? options.resourceType;\n if (explicit && explicit.trim().length > 0) return explicit;\n\n const op = options.operationName;\n if (op && op.trim().length > 0) {\n const [head] = op.split('.');\n if (head && head.trim().length > 0) return head;\n }\n return 'unknown';\n}\n\nfunction readRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n}\n\n/**\n * Resolve the kind of actor behind a tracked operation. Exported for unit tests.\n *\n * Precedence: the explicit `actorType` option, then the request `context` the caller passed\n * (`actor.type`, then the flat `actorType`), then the ambient be-sdk workspace context. A request\n * context is authoritative once given: an unknown kind there yields undefined rather than falling\n * through to the ambient context, which could belong to a different request in the same async\n * chain. A wrong attribution is worse than none.\n */\nexport function resolveTrackedActorType(options: UnifiedTrackingOptions): TrackedActorType | undefined {\n if (options.actorType !== undefined) {\n return isTrackedActorType(options.actorType) ? options.actorType : undefined;\n }\n const context = readRecord(options.context);\n if (context) {\n const actor = readRecord(context['actor']);\n const fromContext = actor?.['type'] ?? context['actorType'];\n return isTrackedActorType(fromContext) ? fromContext : undefined;\n }\n const ambient = getWorkspaceContext()?.actorType;\n return isTrackedActorType(ambient) ? ambient : undefined;\n}\n\nfunction resolveOnBehalfOf(options: UnifiedTrackingOptions): string | undefined {\n if (options.onBehalfOf) return options.onBehalfOf;\n const fromContext = readRecord(options.context)?.['onBehalfOf'];\n return typeof fromContext === 'string' && fromContext.length > 0 ? fromContext : undefined;\n}\n\n/**\n * Resolve the assistant session behind a tracked operation (BOFF-9649). Exported for unit tests.\n *\n * Precedence: the explicit `assistantSession` option, then `context.assistantSession`, then the\n * workspace context bound to the operation's own async scope. The module-level fallback context is\n * never read: it belongs to whichever request built its context last, and tagging a human's row\n * as AI-originated (or the reverse) is worse than leaving it untagged.\n */\nexport function resolveAssistantSession(options: UnifiedTrackingOptions): AssistantSessionAttribution | undefined {\n if (options.assistantSession !== undefined) return readAssistantSessionAttribution(options.assistantSession);\n const fromContext = readAssistantSessionAttribution(readRecord(options.context)?.['assistantSession']);\n if (fromContext) return fromContext;\n return readAssistantSessionAttribution(getScopedWorkspaceContext()?.assistantSession);\n}\n\n/**\n * Input fields an older activity owner may not define yet: wspace-activity-svc before BOFF-9684\n * (`actorType`, `onBehalfOf`), global-activity-svc before BOFF-9649 (assistant-session fields).\n */\nconst ATTRIBUTION_FIELDS = [\n 'actorType',\n 'onBehalfOf',\n 'actorOrigin',\n 'assistantSessionId',\n 'assistantCorrelationId',\n] as const;\n\n/**\n * True when the activity owner rejected the write only because it predates the attribution\n * fields (`Field \"actorType\" is not defined by type \"RecordActivityInput\"`).\n */\nfunction isUnknownAttributionFieldRejection(detail: string): boolean {\n return ATTRIBUTION_FIELDS.some(\n (field) => detail.includes(`\"${field}\"`) && /not defined|unknown field|is not defined by type/i.test(detail)\n );\n}\n\n/**\n * Build the layer-appropriate `RecordActivityInput`.\n *\n * Exported for unit testing: the whole class of defect this guards against is a payload that is\n * structurally plausible but rejected by the owning subgraph, which — because delivery is\n * fire-and-forget — is invisible at runtime.\n */\nexport function buildActivityInput(options: UnifiedTrackingOptions, layer: ActivityLayer): Record<string, unknown> {\n const actOpts = options.activityOptions;\n\n // `action` is REQUIRED by both layers. It is the field that was previously sent as the\n // (non-existent) `activityType`, which made every audit write fail validation.\n const action = actOpts?.activityType ?? options.action ?? options.operationName ?? 'unknown';\n\n const description = actOpts?.description ?? `${options.operationName ?? 'operation'} executed`;\n const resourceType = actOpts?.resourceType ?? options.resourceType;\n const resourceId = actOpts?.resourceId ?? options.resourceId;\n const workspaceId = actOpts?.workspaceId ?? options.workspaceId;\n\n const metadata: Record<string, unknown> = {\n ...actOpts?.metadata,\n success: options.success ?? true,\n ...(options.operationName ? { operationName: options.operationName } : {}),\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n };\n\n const assistantSession = layer === 'global' ? resolveAssistantSession(options) : undefined;\n\n const input: Record<string, unknown> =\n layer === 'global'\n ? {\n action,\n // Required (non-nullable) on global-activity-svc.\n resource: deriveResource(options),\n description,\n resourceType,\n resourceId,\n userId: options.userId,\n actorId: options.userId,\n tenantId: options.tenantId,\n workspaceId,\n metadata,\n // AI-originated change (BOFF-9649): which assistant session made it.\n actorOrigin: assistantSession?.actorOrigin,\n assistantSessionId: assistantSession?.assistantSessionId,\n assistantCorrelationId: assistantSession?.assistantCorrelationId,\n }\n : {\n action,\n description,\n resourceType,\n resourceId,\n workspaceId,\n targetUserId: actOpts?.targetUserId,\n teamId: actOpts?.teamId,\n productId: options.productId,\n success: options.success ?? true,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n metadata: { ...metadata, userId: options.userId },\n // Who acted (BOFF-9684). wspace-activity-svc only; global-activity-svc has no such fields.\n actorType: resolveTrackedActorType(options),\n onBehalfOf: resolveOnBehalfOf(options),\n };\n\n // Both activity owners accept `dedupeKey` and return the existing row when it is replayed, which\n // is what makes delivery retries safe (a timed-out attempt may still have committed).\n input['dedupeKey'] = actOpts?.dedupeKey ?? `sdk:${randomUUID()}`;\n\n return input;\n}\n\n/**\n * Delivery policy for activity writes.\n *\n * A single attempt silently lost audit records whenever the internal gateway or the activity\n * subgraph was briefly unavailable (e.g. during a single-replica rolling deploy): the write timed\n * out, was logged at warn level, and the attributed activity never existed. Writes now retry\n * transient failures with backoff. Retrying is idempotent because every input carries a\n * `dedupeKey` (see {@link buildActivityInput}).\n */\nconst ACTIVITY_ATTEMPT_TIMEOUT_MS = 5000;\nconst DEFAULT_ACTIVITY_RETRY_DELAYS_MS: readonly number[] = [1000, 3000, 8000];\nlet activityRetryDelaysMs: readonly number[] = DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n\n/** HTTP statuses that mean \"the request may not have been processed — try again\". */\nconst RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);\n\n/**\n * GraphQL error codes that describe an unavailable dependency rather than a rejected payload.\n * The internal gateways mask an unreachable subgraph as INTERNAL_SERVER_ERROR, and surface request\n * validation failures as BAD_USER_INPUT (or with no code at all from graphql-js), so a payload the\n * owner rejects is never retried.\n */\nconst RETRYABLE_GRAPHQL_CODES = new Set([\n 'INTERNAL_SERVER_ERROR',\n 'SERVICE_UNAVAILABLE',\n 'AUTH_SERVICE_UNAVAILABLE',\n 'DOWNSTREAM_SERVICE_ERROR',\n 'GATEWAY_TIMEOUT',\n]);\n\n/**\n * Override the retry backoff schedule. Test-only seam so retry behaviour can be exercised without\n * real sleeps; pass `undefined` to restore the default schedule.\n */\nexport function __setActivityRetryDelaysForTests(delaysMs: readonly number[] | undefined): void {\n activityRetryDelaysMs = delaysMs ?? DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n}\n\ntype GraphQLErrorBody = { errors?: Array<{ message?: string; extensions?: { code?: unknown } }> };\n\ntype AttemptOutcome =\n { kind: 'delivered' } | { kind: 'rejected'; detail: string } | { kind: 'transient'; detail: string };\n\nfunction classifyGraphQLErrors(errors: NonNullable<GraphQLErrorBody['errors']>): AttemptOutcome {\n const detail = errors\n .map((e) => e?.message ?? 'unknown error')\n .join('; ')\n .slice(0, 500);\n const transient = errors.every((e) => {\n const code = e?.extensions?.code;\n return typeof code === 'string' && RETRYABLE_GRAPHQL_CODES.has(code);\n });\n return transient ? { kind: 'transient', detail } : { kind: 'rejected', detail };\n}\n\nasync function attemptActivityDelivery(\n gatewayUrl: string,\n headers: Record<string, string>,\n body: string\n): Promise<AttemptOutcome> {\n try {\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: AbortSignal.timeout(ACTIVITY_ATTEMPT_TIMEOUT_MS), // never block the caller for long\n });\n\n if (!response.ok) {\n const detail = `HTTP ${response.status}`;\n return RETRYABLE_HTTP_STATUSES.has(response.status)\n ? { kind: 'transient', detail }\n : { kind: 'rejected', detail };\n }\n\n // A GraphQL validation/execution failure is returned as HTTP 200 with an `errors` array.\n // Without this check a malformed payload is indistinguishable from a successful write, which\n // is exactly how a fleet-wide audit outage stayed invisible: every call \"succeeded\" at the\n // HTTP layer while the subgraph rejected the input.\n const parsed = (await response.json().catch(() => undefined)) as GraphQLErrorBody | undefined;\n const errors = parsed?.errors;\n if (errors && errors.length > 0) {\n return classifyGraphQLErrors(errors);\n }\n return { kind: 'delivered' };\n } catch (err) {\n // Network failure or per-attempt timeout: the write may or may not have landed; the dedupeKey\n // makes a retry safe either way.\n return { kind: 'transient', detail: (err as Error).message };\n }\n}\n\n/**\n * Fire-and-forget activity log via GraphQL, retrying transient failures.\n * Never throws — logs errors and continues.\n */\nasync function fireActivityLog(\n gatewayUrl: string,\n options: UnifiedTrackingOptions,\n layer: ActivityLayer\n): Promise<void> {\n try {\n const actOpts = options.activityOptions;\n const input = buildActivityInput(options, layer);\n\n // Strip undefined values\n for (const key of Object.keys(input)) {\n if (input[key] === undefined) delete input[key];\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Forward actor context if available\n if (options.userId) {\n headers['x-actor-id'] = options.userId;\n headers['x-actor-type'] = 'service';\n }\n if (options.workspaceId ?? actOpts?.workspaceId) {\n headers['x-workspace-id'] = (options.workspaceId ?? actOpts?.workspaceId) as string;\n }\n\n const operation = options.operationName ?? 'operation';\n // Serialize once, outside the retry loop: a payload JSON cannot encode (bigint, cycles) is a\n // deterministic failure and must not be retried as if it were a network error.\n let body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input } });\n let attributionStripped = false;\n const maxAttempts = activityRetryDelaysMs.length + 1;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const outcome = await attemptActivityDelivery(gatewayUrl, headers, body);\n if (outcome.kind === 'delivered') {\n if (attempt > 1) {\n logger.info(`[trackOperation] Activity log delivered on attempt ${attempt}: ${operation}`);\n }\n return;\n }\n if (\n outcome.kind === 'rejected' &&\n !attributionStripped &&\n ATTRIBUTION_FIELDS.some((field) => field in input) &&\n isUnknownAttributionFieldRejection(outcome.detail)\n ) {\n // The owner predates the attribution fields (rollout skew). Losing the audit row would\n // be worse than losing who-acted on it, so resend once without them.\n attributionStripped = true;\n const stripped = { ...input };\n for (const field of ATTRIBUTION_FIELDS) delete stripped[field];\n body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input: stripped } });\n logger.warn(\n `[trackOperation] ${layer}-activity subgraph does not accept the actor attribution fields yet; resending \"${operation}\" without them`\n );\n attempt -= 1;\n continue;\n }\n if (outcome.kind === 'rejected') {\n logger.error(\n `[trackOperation] Activity log REJECTED by ${layer}-activity subgraph for \"${operation}\": ${outcome.detail}`\n );\n return;\n }\n const delay = activityRetryDelaysMs[attempt - 1];\n if (delay === undefined) {\n // An audit record is about to be lost: this must be visible at error level.\n logger.error(\n `[trackOperation] Activity log failed after ${attempt} attempts for \"${operation}\": ${outcome.detail}`\n );\n return;\n }\n logger.warn(\n `[trackOperation] Activity log attempt ${attempt} failed for \"${operation}\" (${outcome.detail}); retrying in ${delay}ms`\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n } catch (err) {\n // Fire-and-forget: log but never throw\n logger.warn(`[trackOperation] Activity log failed: ${(err as Error).message}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main trackOperation function\n// ---------------------------------------------------------------------------\n\n/**\n * Simple tracker class with auto-promoting behavior\n */\nexport class UnifiedTrackerStub {\n private static instance: UnifiedTrackerStub;\n\n static getInstance(): UnifiedTrackerStub {\n if (!UnifiedTrackerStub.instance) {\n UnifiedTrackerStub.instance = new UnifiedTrackerStub();\n }\n return UnifiedTrackerStub.instance;\n }\n\n async track(event: TrackingEvent): Promise<void> {\n markExplicitActivity();\n const gatewayUrl = getGatewayUrl();\n if (gatewayUrl) {\n await fireActivityLog(\n gatewayUrl,\n {\n operationName: event.eventType,\n userId: event.userId,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n activityOptions: {\n activityType: event.eventType,\n metadata: event.metadata,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n enabled: true,\n },\n },\n getGatewayLayer()\n );\n } else {\n logger.debug('[UnifiedTracker:Stub]', event.eventType, event.entityType, event.entityId);\n }\n }\n\n async trackBatch(events: TrackingEvent[]): Promise<void> {\n for (const event of events) {\n await this.track(event);\n }\n }\n}\n\nexport const trackerStub = UnifiedTrackerStub.getInstance();\n\n/**\n * Unified tracking function — auto-promoting\n *\n * When a gateway URL is configured (WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL),\n * this function makes real fire-and-forget GraphQL calls for activity logging.\n * When no gateway URL is configured, it falls back to debug-level logging (stub mode).\n *\n * RBAC checks are NOT performed here — they are handled by gateway @rbac directives.\n * The rbacCheck option is accepted for interface compatibility but not enforced.\n *\n * @param options - Tracking options\n * @returns Always returns true (never blocks the calling operation)\n */\nexport async function trackOperation(options: UnifiedTrackingOptions): Promise<boolean> {\n const { operationName, userId, success = true } = options;\n const gatewayUrl = getGatewayUrl();\n const activityEnabled = options.activityOptions?.enabled !== false;\n\n // An explicit activity write: the mutation-audit backstop must not add a second row for this\n // operation. Marked in stub mode too, so dedupe behaves the same locally as when deployed.\n if (activityEnabled) markExplicitActivity();\n\n if (!gatewayUrl) {\n // Stub mode — debug log only\n logger.debug(`[trackOperation:Stub] ${operationName} for user ${userId} - success: ${success}`);\n return true;\n }\n\n // Real mode — fire-and-forget activity logging\n if (activityEnabled) {\n // Do NOT await — fire and forget so we never block the caller\n void fireActivityLog(gatewayUrl, options, getGatewayLayer());\n } else {\n logger.debug(`[trackOperation] ${operationName} for user ${userId} - activity disabled, skipping`);\n }\n\n return true;\n}\n\n/**\n * Product tracker type definition\n */\nexport type ProductTracker = {\n track: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n freeUp: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackActivityOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackUsageOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackCustom: (operationName: string, additionalOptions: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n productId: string;\n userId: string;\n billingAccountId: string | undefined;\n defaultContext: Partial<UnifiedTrackingOptions> | undefined;\n};\n\n/**\n * Create a product-scoped tracker (auto-promoting implementation)\n *\n * @param productId - Product identifier\n * @param userId - User identifier\n * @param billingAccountId - Optional billing account ID\n * @param defaultContext - Optional default tracking context\n * @returns Product tracker instance\n */\nexport function createProductTracker(\n productId: string,\n userId: string,\n billingAccountId?: string,\n defaultContext?: Partial<UnifiedTrackingOptions>\n): ProductTracker {\n return {\n async track(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n async freeUp(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: {\n ...defaultContext?.activityOptions,\n ...additionalOptions?.activityOptions,\n activityType: 'free_up',\n },\n });\n },\n async trackActivityOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { ...defaultContext?.activityOptions, ...additionalOptions?.activityOptions, enabled: true },\n usageOptions: { enabled: false },\n });\n },\n async trackUsageOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { enabled: false },\n usageOptions: { ...defaultContext?.usageOptions, ...additionalOptions?.usageOptions, enabled: true },\n });\n },\n async trackCustom(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n productId,\n userId,\n billingAccountId,\n defaultContext,\n };\n}\n\n/**\n * Constants for tracking\n */\nexport const UNIFIED_TRACKER_CONSTANTS = {\n DEFAULT_PRODUCT_ID: 'module',\n OPERATIONS: {} as const,\n PRODUCTS: {} as const,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,4BAA4B;;AAKzC,MAAa,sBAAsB;AACnC,MAAa,8BAA8B;AAC3C,MAAa,kCAAkC;;AAG/C,MAAM,yBAAyB;AAW/B,SAAS,cAAc,OAAoC;CACzD,OAAO,OAAO,UAAU,YAAY,uBAAuB,KAAK,KAAK,IAAI,QAAQ;AACnF;;;;;;AAOA,SAAgB,8BACd,aACA,oBACA,wBACyC;CACzC,IAAI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AiB,EAAE,SAAS,MAAM;IAClC,cAAc;KAAE,GAAG,gBAAgB;KAAc,GAAG,mBAAmB;KAAc,SAAS;IAAK;GACrG,CAAC;EACH;EACA,MAAM,YAAY,eAAe,mBAAqC;GACpE,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;GACL,CAAC;EACH;EACA;EACA;EACA;EACA;CACF;AACF;;;;AAKA,MAAa,4BAA4B;CACvC,oBAAoB;CACpB,YAAY,CAAC;CACb,UAAU,CAAC;AACb"}
1
+ {"version":3,"file":"stub-DNkzpQvR.js","names":[],"sources":["../src/activity/assistant-session.ts","../src/tracker/stub.ts"],"sourcesContent":["/**\n * Assistant-session attribution (BOFF-9649)\n *\n * When an AI assistant session runs a GraphQL mutation for its owner, the\n * assistant session relay (wspace-sandbox-svc) forwards it to a public gateway\n * as the owner, with a signed assistant-session marker. The gateway verifies\n * that marker against the owner's verified token, strips any copy a client\n * sent, and passes the result to subgraphs as three headers:\n *\n * x-actor-origin: ai_assistant\n * x-assistant-session-id: <the relay session id (the assistant sandbox id)>\n * x-assistant-correlation-id: <the proposal / idempotency key, when there is one>\n *\n * A service never verifies these itself. `buildContext` reads them only when it\n * already trusts the gateway's actor headers, exposes them as\n * `context.assistantSession`, and binds them to the operation's workspace\n * context so `trackOperation` can stamp every activity row written while the\n * operation runs, without each service re-implementing audit.\n *\n * Values outside the vocabulary or the id pattern are dropped, never coerced:\n * a wrong attribution is worse than none.\n */\n\n/** The only actor origin the platform records today. */\nexport const AI_ASSISTANT_ACTOR_ORIGIN = 'ai_assistant';\n\nexport type ActorOrigin = typeof AI_ASSISTANT_ACTOR_ORIGIN;\n\n/** Gateway-to-subgraph headers. Clients cannot set them: the public gateways strip them. */\nexport const ACTOR_ORIGIN_HEADER = 'x-actor-origin';\nexport const ASSISTANT_SESSION_ID_HEADER = 'x-assistant-session-id';\nexport const ASSISTANT_CORRELATION_ID_HEADER = 'x-assistant-correlation-id';\n\n/** Session ids (UUIDs, cuid-style ids) and proposal / idempotency keys. */\nconst ATTRIBUTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** The assistant session an operation ran under. */\nexport interface AssistantSessionAttribution {\n actorOrigin: ActorOrigin;\n /** The relay session id: the assistant sandbox that ran the mutation. */\n assistantSessionId: string;\n /** The proposal / idempotency key the mutation ran under, when it had one. */\n assistantCorrelationId?: string;\n}\n\nfunction attributionId(value: unknown): string | undefined {\n return typeof value === 'string' && ATTRIBUTION_ID_PATTERN.test(value) ? value : undefined;\n}\n\n/**\n * Build an attribution from raw values. Undefined unless the origin is\n * `ai_assistant` and the session id is well formed; a malformed correlation id\n * is dropped on its own.\n */\nexport function toAssistantSessionAttribution(\n actorOrigin: unknown,\n assistantSessionId: unknown,\n assistantCorrelationId?: unknown\n): AssistantSessionAttribution | undefined {\n if (actorOrigin !== AI_ASSISTANT_ACTOR_ORIGIN) return undefined;\n const sessionId = attributionId(assistantSessionId);\n if (!sessionId) return undefined;\n const correlationId = attributionId(assistantCorrelationId);\n return {\n actorOrigin: AI_ASSISTANT_ACTOR_ORIGIN,\n assistantSessionId: sessionId,\n ...(correlationId ? { assistantCorrelationId: correlationId } : {}),\n };\n}\n\n/**\n * Read the gateway's assistant-session headers. The caller decides whether the\n * request's gateway headers are trusted at all; this only parses them.\n */\nexport function parseAssistantSessionHeaders(\n getHeader: (name: string) => string | null | undefined\n): AssistantSessionAttribution | undefined {\n return toAssistantSessionAttribution(\n getHeader(ACTOR_ORIGIN_HEADER),\n getHeader(ASSISTANT_SESSION_ID_HEADER),\n getHeader(ASSISTANT_CORRELATION_ID_HEADER)\n );\n}\n\n/** Re-validate an attribution-shaped value (from a request context or caller options). */\nexport function readAssistantSessionAttribution(value: unknown): AssistantSessionAttribution | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Record<string, unknown>;\n return toAssistantSessionAttribution(\n record['actorOrigin'],\n record['assistantSessionId'],\n record['assistantCorrelationId']\n );\n}\n","/**\n * Unified Tracking — Auto-Promoting Implementation\n *\n * Automatically promotes from stub to real tracking when gateway URLs are configured.\n * When WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL is set, this module will:\n * - Log activity events via GraphQL to the activity service\n * - Track usage via GraphQL to the usage service (if usage options provided)\n * - RBAC checks are NOT performed here (handled by gateway @rbac directives)\n *\n * When no gateway URL is configured, falls back to debug-level logging (stub mode).\n *\n * This is a backward-compatible drop-in replacement for the original stub. All 1,100+\n * existing call sites continue to work without modification.\n *\n * @module tracker/stub\n * @category Tracking\n */\nimport { randomUUID } from 'node:crypto';\n\nimport { logger } from '../logger/index.js';\nimport { markExplicitActivity } from '../activity/explicit-activity-scope.js';\nimport { readAssistantSessionAttribution, type AssistantSessionAttribution } from '../activity/assistant-session.js';\nimport { getScopedWorkspaceContext, getWorkspaceContext } from '../prisma/workspace-extension.js';\n\n/**\n * Tracking event interface\n */\nexport interface TrackingEvent {\n eventType: string;\n entityType: string;\n entityId: string;\n userId?: string;\n workspaceId?: string;\n metadata?: Record<string, unknown>;\n timestamp?: Date;\n}\n\n/**\n * RBAC check options\n */\nexport interface RbacCheckOptions {\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n skipRbacCheck?: boolean;\n options?: {\n allowOwnerAccess?: boolean;\n allowWorkspaceAdmin?: boolean;\n scope?: string;\n };\n}\n\n/**\n * Usage tracking options\n */\nexport interface UsageTrackingOptions {\n billingAccountId?: string;\n addUsage?: boolean;\n description?: string;\n tags?: Record<string, unknown>;\n quotaName?: string;\n value?: number;\n}\n\n/**\n * Activity tracking options\n */\nexport interface ActivityTrackingOptions {\n activityType?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n workspaceId?: string;\n teamId?: string;\n groupId?: string;\n projectId?: string;\n targetUserId?: string;\n resourceType?: string;\n resourceId?: string;\n enabled?: boolean;\n /**\n * Idempotency key forwarded to the activity owner's `RecordActivityInput.dedupeKey`.\n * When omitted, a unique key is generated per tracked operation so that delivery retries of the\n * SAME operation converge to exactly one activity row. Supply a stable key only when the caller\n * itself may replay the same logical event (backfill/import).\n */\n dedupeKey?: string;\n}\n\n/**\n * Kind of actor behind a tracked operation — the gateway `x-actor-type` vocabulary.\n *\n * An AI agent acting through a product service is an `app` actor; recording it lets the\n * activity owner tell agent actions apart from human ones (BOFF-9684).\n */\nexport type TrackedActorType = 'user' | 'app' | 'service' | 'super_admin';\n\nconst TRACKED_ACTOR_TYPES: ReadonlySet<string> = new Set<TrackedActorType>(['user', 'app', 'service', 'super_admin']);\n\nexport function isTrackedActorType(value: unknown): value is TrackedActorType {\n return typeof value === 'string' && TRACKED_ACTOR_TYPES.has(value);\n}\n\n/**\n * Unified tracking options\n */\nexport interface UnifiedTrackingOptions {\n operationName?: string;\n userId?: string;\n /**\n * Kind of actor `userId` identifies. When omitted it is taken from `context` (`actor.type` or\n * `actorType`) or, with no `context`, from the ambient be-sdk workspace context; a value outside\n * the vocabulary is dropped rather than sent. The activity owner honours it because the tracker\n * calls it as a relaying `service`.\n */\n actorType?: TrackedActorType;\n /**\n * The user on whose behalf `userId` acted — for an AI-agent action, the human who started the\n * run. When omitted it is taken from `context.onBehalfOf`; the activity owner otherwise records\n * the actor itself.\n */\n onBehalfOf?: string;\n /**\n * The AI assistant session the operation ran under (BOFF-9649). When omitted it is taken from\n * `context.assistantSession` or, failing that, from the operation's own async scope (never from\n * another request's). Sent to global-activity-svc as `actorOrigin` / `assistantSessionId` /\n * `assistantCorrelationId`.\n */\n assistantSession?: AssistantSessionAttribution;\n context?: unknown;\n rbacCheck?: RbacCheckOptions;\n activityOptions?: ActivityTrackingOptions;\n usageOptions?: UsageTrackingOptions & { enabled?: boolean };\n success?: boolean;\n errorMessage?: string;\n productId?: string;\n // Legacy properties for backward compatibility (can be at top level or in nested objects)\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n tenantId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Gateway URL resolution — cached at module level for performance\n// ---------------------------------------------------------------------------\n\nlet _gatewayUrl: string | undefined;\nlet _gatewayLayer: ActivityLayer | undefined;\nlet _gatewayUrlResolved = false;\n\n/**\n * Which activity subgraph the resolved gateway fronts.\n *\n * The two canonical activity owners accept DIFFERENT `RecordActivityInput` shapes, so the\n * payload must be built per layer:\n * - `wspace` → wspace-activity-svc: requires `action`; carries workspace-scoped fields\n * (workspaceId/teamId/targetUserId/productId/success).\n * - `global` → global-activity-svc: requires `action` AND `resource`; carries tenant-scoped\n * fields (tenantId/actorId/ipAddress/userAgent).\n * Sending one layer's shape to the other fails GraphQL validation.\n */\nexport type ActivityLayer = 'wspace' | 'global';\n\n/**\n * The layer the running service belongs to, when its environment says so: `SERVICE_LAYER`, then a\n * `global-` / `wspace-` `SERVICE_NAME` prefix (the same rule the RBAC directive and the Temporal\n * client use). Undefined when neither says.\n */\nfunction declaredServiceLayer(): ActivityLayer | undefined {\n const layer = process.env['SERVICE_LAYER'];\n if (layer === 'global' || layer === 'wspace') return layer;\n const name = process.env['SERVICE_NAME'] ?? '';\n if (name.startsWith('global-')) return 'global';\n if (name.startsWith('wspace-')) return 'wspace';\n return undefined;\n}\n\n/**\n * Resolve the internal gateway URL from environment.\n *\n * Activity belongs to the service's OWN layer: workspace services record in wspace-activity-svc\n * through WSPACE_INT_GATEWAY_URL, global services in global-activity-svc through\n * GLOBAL_INT_GATEWAY_URL. Global services also hold WSPACE_INT_GATEWAY_URL for cross-layer\n * calls, so the URL that happens to be set is not a layer signal: the declared layer\n * (`SERVICE_LAYER` / `SERVICE_NAME`) decides, and only an undeclared service falls back to\n * \"workspace URL first\" (BOFF-9649 — every global service was sending its audit rows to the\n * workspace activity owner, which rejected them). Undefined (stub mode) when no URL is set.\n */\nfunction getGatewayUrl(): string | undefined {\n if (!_gatewayUrlResolved) {\n const wspaceUrl = process.env['WSPACE_INT_GATEWAY_URL'];\n const globalUrl = process.env['GLOBAL_INT_GATEWAY_URL'];\n const declared = declaredServiceLayer();\n\n // A declared global service uses its own owner; anything else keeps \"workspace URL first\".\n const useGlobal = Boolean(globalUrl) && (declared === 'global' || !wspaceUrl);\n if (useGlobal) {\n _gatewayUrl = globalUrl;\n _gatewayLayer = 'global';\n } else if (wspaceUrl) {\n _gatewayUrl = wspaceUrl;\n _gatewayLayer = 'wspace';\n } else {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n }\n if (declared && _gatewayLayer && declared !== _gatewayLayer) {\n logger.warn(\n `[trackOperation] ${declared} service has no ${declared === 'global' ? 'GLOBAL' : 'WSPACE'}_INT_GATEWAY_URL; activity goes to the ${_gatewayLayer} activity owner instead`\n );\n }\n _gatewayUrlResolved = true;\n\n if (_gatewayUrl) {\n logger.info(`[trackOperation] Real tracking enabled via ${_gatewayLayer} gateway: ${_gatewayUrl}`);\n } else {\n logger.debug('[trackOperation] No gateway URL configured — running in stub mode');\n }\n }\n return _gatewayUrl;\n}\n\n/**\n * Resolve which activity layer the configured gateway fronts.\n * Always call `getGatewayUrl()` first — it performs the resolution.\n */\nfunction getGatewayLayer(): ActivityLayer {\n // Default to 'wspace': the overwhelming majority of services are workspace-layer, and a wspace\n // payload omits only optional global fields, so a mis-detection degrades rather than fails.\n return _gatewayLayer ?? 'wspace';\n}\n\n/**\n * Reset the cached gateway resolution. Test-only seam — module-level caching would otherwise make\n * per-layer behaviour untestable within a single process.\n */\nexport function __resetGatewayCacheForTests(): void {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n _gatewayUrlResolved = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fire-and-forget GraphQL helper\n// ---------------------------------------------------------------------------\n\nconst LOG_ACTIVITY_MUTATION = /* GraphQL */ `\n mutation RecordActivity($input: RecordActivityInput!) {\n recordActivity(input: $input) {\n id\n }\n }\n`;\n\n/**\n * Derive the `resource` value required by global-activity-svc.\n *\n * Prefers an explicit resourceType; otherwise falls back to the leading dotted segment of the\n * operation name (`auth.session.revoke` → `auth`), which matches the platform's\n * `<domain>.<resource>.<verb>` activity taxonomy. Never returns empty — `resource` is non-nullable\n * on global-activity-svc and an empty string would be silently useless in the audit trail.\n */\nfunction deriveResource(options: UnifiedTrackingOptions): string {\n const explicit = options.activityOptions?.resourceType ?? options.resourceType;\n if (explicit && explicit.trim().length > 0) return explicit;\n\n const op = options.operationName;\n if (op && op.trim().length > 0) {\n const [head] = op.split('.');\n if (head && head.trim().length > 0) return head;\n }\n return 'unknown';\n}\n\nfunction readRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n}\n\n/**\n * Resolve the kind of actor behind a tracked operation. Exported for unit tests.\n *\n * Precedence: the explicit `actorType` option, then the request `context` the caller passed\n * (`actor.type`, then the flat `actorType`), then the ambient be-sdk workspace context. A request\n * context is authoritative once given: an unknown kind there yields undefined rather than falling\n * through to the ambient context, which could belong to a different request in the same async\n * chain. A wrong attribution is worse than none.\n */\nexport function resolveTrackedActorType(options: UnifiedTrackingOptions): TrackedActorType | undefined {\n if (options.actorType !== undefined) {\n return isTrackedActorType(options.actorType) ? options.actorType : undefined;\n }\n const context = readRecord(options.context);\n if (context) {\n const actor = readRecord(context['actor']);\n const fromContext = actor?.['type'] ?? context['actorType'];\n return isTrackedActorType(fromContext) ? fromContext : undefined;\n }\n const ambient = getWorkspaceContext()?.actorType;\n return isTrackedActorType(ambient) ? ambient : undefined;\n}\n\nfunction resolveOnBehalfOf(options: UnifiedTrackingOptions): string | undefined {\n if (options.onBehalfOf) return options.onBehalfOf;\n const fromContext = readRecord(options.context)?.['onBehalfOf'];\n return typeof fromContext === 'string' && fromContext.length > 0 ? fromContext : undefined;\n}\n\n/**\n * Resolve the assistant session behind a tracked operation (BOFF-9649). Exported for unit tests.\n *\n * Precedence: the explicit `assistantSession` option, then `context.assistantSession`, then the\n * workspace context bound to the operation's own async scope. The module-level fallback context is\n * never read: it belongs to whichever request built its context last, and tagging a human's row\n * as AI-originated (or the reverse) is worse than leaving it untagged.\n */\nexport function resolveAssistantSession(options: UnifiedTrackingOptions): AssistantSessionAttribution | undefined {\n if (options.assistantSession !== undefined) return readAssistantSessionAttribution(options.assistantSession);\n const fromContext = readAssistantSessionAttribution(readRecord(options.context)?.['assistantSession']);\n if (fromContext) return fromContext;\n return readAssistantSessionAttribution(getScopedWorkspaceContext()?.assistantSession);\n}\n\n/**\n * Input fields an older activity owner may not define yet: wspace-activity-svc before BOFF-9684\n * (`actorType`, `onBehalfOf`), global-activity-svc before BOFF-9649 (assistant-session fields).\n */\nconst ATTRIBUTION_FIELDS = [\n 'actorType',\n 'onBehalfOf',\n 'actorOrigin',\n 'assistantSessionId',\n 'assistantCorrelationId',\n] as const;\n\n/**\n * True when the activity owner rejected the write only because it predates the attribution\n * fields (`Field \"actorType\" is not defined by type \"RecordActivityInput\"`).\n */\nfunction isUnknownAttributionFieldRejection(detail: string): boolean {\n return ATTRIBUTION_FIELDS.some(\n (field) => detail.includes(`\"${field}\"`) && /not defined|unknown field|is not defined by type/i.test(detail)\n );\n}\n\n/**\n * Build the layer-appropriate `RecordActivityInput`.\n *\n * Exported for unit testing: the whole class of defect this guards against is a payload that is\n * structurally plausible but rejected by the owning subgraph, which — because delivery is\n * fire-and-forget — is invisible at runtime.\n */\nexport function buildActivityInput(options: UnifiedTrackingOptions, layer: ActivityLayer): Record<string, unknown> {\n const actOpts = options.activityOptions;\n\n // `action` is REQUIRED by both layers. It is the field that was previously sent as the\n // (non-existent) `activityType`, which made every audit write fail validation.\n const action = actOpts?.activityType ?? options.action ?? options.operationName ?? 'unknown';\n\n const description = actOpts?.description ?? `${options.operationName ?? 'operation'} executed`;\n const resourceType = actOpts?.resourceType ?? options.resourceType;\n const resourceId = actOpts?.resourceId ?? options.resourceId;\n const workspaceId = actOpts?.workspaceId ?? options.workspaceId;\n\n const metadata: Record<string, unknown> = {\n ...actOpts?.metadata,\n success: options.success ?? true,\n ...(options.operationName ? { operationName: options.operationName } : {}),\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n };\n\n const assistantSession = layer === 'global' ? resolveAssistantSession(options) : undefined;\n\n const input: Record<string, unknown> =\n layer === 'global'\n ? {\n action,\n // Required (non-nullable) on global-activity-svc.\n resource: deriveResource(options),\n description,\n resourceType,\n resourceId,\n userId: options.userId,\n actorId: options.userId,\n tenantId: options.tenantId,\n workspaceId,\n metadata,\n // AI-originated change (BOFF-9649): which assistant session made it.\n actorOrigin: assistantSession?.actorOrigin,\n assistantSessionId: assistantSession?.assistantSessionId,\n assistantCorrelationId: assistantSession?.assistantCorrelationId,\n }\n : {\n action,\n description,\n resourceType,\n resourceId,\n workspaceId,\n targetUserId: actOpts?.targetUserId,\n teamId: actOpts?.teamId,\n productId: options.productId,\n success: options.success ?? true,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n metadata: { ...metadata, userId: options.userId },\n // Who acted (BOFF-9684). wspace-activity-svc only; global-activity-svc has no such fields.\n actorType: resolveTrackedActorType(options),\n onBehalfOf: resolveOnBehalfOf(options),\n };\n\n // Both activity owners accept `dedupeKey` and return the existing row when it is replayed, which\n // is what makes delivery retries safe (a timed-out attempt may still have committed).\n input['dedupeKey'] = actOpts?.dedupeKey ?? `sdk:${randomUUID()}`;\n\n return input;\n}\n\n/**\n * Delivery policy for activity writes.\n *\n * A single attempt silently lost audit records whenever the internal gateway or the activity\n * subgraph was briefly unavailable (e.g. during a single-replica rolling deploy): the write timed\n * out, was logged at warn level, and the attributed activity never existed. Writes now retry\n * transient failures with backoff. Retrying is idempotent because every input carries a\n * `dedupeKey` (see {@link buildActivityInput}).\n */\nconst ACTIVITY_ATTEMPT_TIMEOUT_MS = 5000;\nconst DEFAULT_ACTIVITY_RETRY_DELAYS_MS: readonly number[] = [1000, 3000, 8000];\nlet activityRetryDelaysMs: readonly number[] = DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n\n/** HTTP statuses that mean \"the request may not have been processed — try again\". */\nconst RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);\n\n/**\n * GraphQL error codes that describe an unavailable dependency rather than a rejected payload.\n * The internal gateways mask an unreachable subgraph as INTERNAL_SERVER_ERROR, and surface request\n * validation failures as BAD_USER_INPUT (or with no code at all from graphql-js), so a payload the\n * owner rejects is never retried.\n */\nconst RETRYABLE_GRAPHQL_CODES = new Set([\n 'INTERNAL_SERVER_ERROR',\n 'SERVICE_UNAVAILABLE',\n 'AUTH_SERVICE_UNAVAILABLE',\n 'DOWNSTREAM_SERVICE_ERROR',\n 'GATEWAY_TIMEOUT',\n]);\n\n/**\n * Override the retry backoff schedule. Test-only seam so retry behaviour can be exercised without\n * real sleeps; pass `undefined` to restore the default schedule.\n */\nexport function __setActivityRetryDelaysForTests(delaysMs: readonly number[] | undefined): void {\n activityRetryDelaysMs = delaysMs ?? DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n}\n\ntype GraphQLErrorBody = { errors?: Array<{ message?: string; extensions?: { code?: unknown } }> };\n\ntype AttemptOutcome =\n { kind: 'delivered' } | { kind: 'rejected'; detail: string } | { kind: 'transient'; detail: string };\n\nfunction classifyGraphQLErrors(errors: NonNullable<GraphQLErrorBody['errors']>): AttemptOutcome {\n const detail = errors\n .map((e) => e?.message ?? 'unknown error')\n .join('; ')\n .slice(0, 500);\n const transient = errors.every((e) => {\n const code = e?.extensions?.code;\n return typeof code === 'string' && RETRYABLE_GRAPHQL_CODES.has(code);\n });\n return transient ? { kind: 'transient', detail } : { kind: 'rejected', detail };\n}\n\nasync function attemptActivityDelivery(\n gatewayUrl: string,\n headers: Record<string, string>,\n body: string\n): Promise<AttemptOutcome> {\n try {\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: AbortSignal.timeout(ACTIVITY_ATTEMPT_TIMEOUT_MS), // never block the caller for long\n });\n\n if (!response.ok) {\n const detail = `HTTP ${response.status}`;\n return RETRYABLE_HTTP_STATUSES.has(response.status)\n ? { kind: 'transient', detail }\n : { kind: 'rejected', detail };\n }\n\n // A GraphQL validation/execution failure is returned as HTTP 200 with an `errors` array.\n // Without this check a malformed payload is indistinguishable from a successful write, which\n // is exactly how a fleet-wide audit outage stayed invisible: every call \"succeeded\" at the\n // HTTP layer while the subgraph rejected the input.\n const parsed = (await response.json().catch(() => undefined)) as GraphQLErrorBody | undefined;\n const errors = parsed?.errors;\n if (errors && errors.length > 0) {\n return classifyGraphQLErrors(errors);\n }\n return { kind: 'delivered' };\n } catch (err) {\n // Network failure or per-attempt timeout: the write may or may not have landed; the dedupeKey\n // makes a retry safe either way.\n return { kind: 'transient', detail: (err as Error).message };\n }\n}\n\n/**\n * Fire-and-forget activity log via GraphQL, retrying transient failures.\n * Never throws — logs errors and continues.\n */\nasync function fireActivityLog(\n gatewayUrl: string,\n options: UnifiedTrackingOptions,\n layer: ActivityLayer\n): Promise<void> {\n try {\n const actOpts = options.activityOptions;\n const input = buildActivityInput(options, layer);\n\n // Strip undefined values\n for (const key of Object.keys(input)) {\n if (input[key] === undefined) delete input[key];\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Forward actor context if available\n if (options.userId) {\n headers['x-actor-id'] = options.userId;\n headers['x-actor-type'] = 'service';\n }\n if (options.workspaceId ?? actOpts?.workspaceId) {\n headers['x-workspace-id'] = (options.workspaceId ?? actOpts?.workspaceId) as string;\n }\n\n const operation = options.operationName ?? 'operation';\n // Serialize once, outside the retry loop: a payload JSON cannot encode (bigint, cycles) is a\n // deterministic failure and must not be retried as if it were a network error.\n let body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input } });\n let attributionStripped = false;\n const maxAttempts = activityRetryDelaysMs.length + 1;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const outcome = await attemptActivityDelivery(gatewayUrl, headers, body);\n if (outcome.kind === 'delivered') {\n if (attempt > 1) {\n logger.info(`[trackOperation] Activity log delivered on attempt ${attempt}: ${operation}`);\n }\n return;\n }\n if (\n outcome.kind === 'rejected' &&\n !attributionStripped &&\n ATTRIBUTION_FIELDS.some((field) => field in input) &&\n isUnknownAttributionFieldRejection(outcome.detail)\n ) {\n // The owner predates the attribution fields (rollout skew). Losing the audit row would\n // be worse than losing who-acted on it, so resend once without them.\n attributionStripped = true;\n const stripped = { ...input };\n for (const field of ATTRIBUTION_FIELDS) delete stripped[field];\n body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input: stripped } });\n logger.warn(\n `[trackOperation] ${layer}-activity subgraph does not accept the actor attribution fields yet; resending \"${operation}\" without them`\n );\n attempt -= 1;\n continue;\n }\n if (outcome.kind === 'rejected') {\n logger.error(\n `[trackOperation] Activity log REJECTED by ${layer}-activity subgraph for \"${operation}\": ${outcome.detail}`\n );\n return;\n }\n const delay = activityRetryDelaysMs[attempt - 1];\n if (delay === undefined) {\n // An audit record is about to be lost: this must be visible at error level.\n logger.error(\n `[trackOperation] Activity log failed after ${attempt} attempts for \"${operation}\": ${outcome.detail}`\n );\n return;\n }\n logger.warn(\n `[trackOperation] Activity log attempt ${attempt} failed for \"${operation}\" (${outcome.detail}); retrying in ${delay}ms`\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n } catch (err) {\n // Fire-and-forget: log but never throw\n logger.warn(`[trackOperation] Activity log failed: ${(err as Error).message}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main trackOperation function\n// ---------------------------------------------------------------------------\n\n/**\n * Simple tracker class with auto-promoting behavior\n */\nexport class UnifiedTrackerStub {\n private static instance: UnifiedTrackerStub;\n\n static getInstance(): UnifiedTrackerStub {\n if (!UnifiedTrackerStub.instance) {\n UnifiedTrackerStub.instance = new UnifiedTrackerStub();\n }\n return UnifiedTrackerStub.instance;\n }\n\n async track(event: TrackingEvent): Promise<void> {\n markExplicitActivity();\n const gatewayUrl = getGatewayUrl();\n if (gatewayUrl) {\n await fireActivityLog(\n gatewayUrl,\n {\n operationName: event.eventType,\n userId: event.userId,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n activityOptions: {\n activityType: event.eventType,\n metadata: event.metadata,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n enabled: true,\n },\n },\n getGatewayLayer()\n );\n } else {\n logger.debug('[UnifiedTracker:Stub]', event.eventType, event.entityType, event.entityId);\n }\n }\n\n async trackBatch(events: TrackingEvent[]): Promise<void> {\n for (const event of events) {\n await this.track(event);\n }\n }\n}\n\nexport const trackerStub = UnifiedTrackerStub.getInstance();\n\n/**\n * Unified tracking function — auto-promoting\n *\n * When a gateway URL is configured (WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL),\n * this function makes real fire-and-forget GraphQL calls for activity logging.\n * When no gateway URL is configured, it falls back to debug-level logging (stub mode).\n *\n * RBAC checks are NOT performed here — they are handled by gateway @rbac directives.\n * The rbacCheck option is accepted for interface compatibility but not enforced.\n *\n * @param options - Tracking options\n * @returns Always returns true (never blocks the calling operation)\n */\nexport async function trackOperation(options: UnifiedTrackingOptions): Promise<boolean> {\n const { operationName, userId, success = true } = options;\n const gatewayUrl = getGatewayUrl();\n const activityEnabled = options.activityOptions?.enabled !== false;\n\n // An explicit activity write: the mutation-audit backstop must not add a second row for this\n // operation. Marked in stub mode too, so dedupe behaves the same locally as when deployed.\n if (activityEnabled) markExplicitActivity();\n\n if (!gatewayUrl) {\n // Stub mode — debug log only\n logger.debug(`[trackOperation:Stub] ${operationName} for user ${userId} - success: ${success}`);\n return true;\n }\n\n // Real mode — fire-and-forget activity logging\n if (activityEnabled) {\n // Do NOT await — fire and forget so we never block the caller\n void fireActivityLog(gatewayUrl, options, getGatewayLayer());\n } else {\n logger.debug(`[trackOperation] ${operationName} for user ${userId} - activity disabled, skipping`);\n }\n\n return true;\n}\n\n/**\n * Product tracker type definition\n */\nexport type ProductTracker = {\n track: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n freeUp: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackActivityOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackUsageOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackCustom: (operationName: string, additionalOptions: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n productId: string;\n userId: string;\n billingAccountId: string | undefined;\n defaultContext: Partial<UnifiedTrackingOptions> | undefined;\n};\n\n/**\n * Create a product-scoped tracker (auto-promoting implementation)\n *\n * @param productId - Product identifier\n * @param userId - User identifier\n * @param billingAccountId - Optional billing account ID\n * @param defaultContext - Optional default tracking context\n * @returns Product tracker instance\n */\nexport function createProductTracker(\n productId: string,\n userId: string,\n billingAccountId?: string,\n defaultContext?: Partial<UnifiedTrackingOptions>\n): ProductTracker {\n return {\n async track(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n async freeUp(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: {\n ...defaultContext?.activityOptions,\n ...additionalOptions?.activityOptions,\n activityType: 'free_up',\n },\n });\n },\n async trackActivityOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { ...defaultContext?.activityOptions, ...additionalOptions?.activityOptions, enabled: true },\n usageOptions: { enabled: false },\n });\n },\n async trackUsageOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { enabled: false },\n usageOptions: { ...defaultContext?.usageOptions, ...additionalOptions?.usageOptions, enabled: true },\n });\n },\n async trackCustom(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n productId,\n userId,\n billingAccountId,\n defaultContext,\n };\n}\n\n/**\n * Constants for tracking\n */\nexport const UNIFI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G;IACH,iBAAiB;KACf,GAAG,gBAAgB;KACnB,GAAG,mBAAmB;KACtB,cAAc;IAChB;GACF,CAAC;EACH;EACA,MAAM,kBAAkB,eAAe,mBAAqC;GAC1E,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;IACH,iBAAiB;KAAE,GAAG,gBAAgB;KAAiB,GAAG,mBAAmB;KAAiB,SAAS;IAAK;IAC5G,cAAc,EAAE,SAAS,MAAM;GACjC,CAAC;EACH;EACA,MAAM,eAAe,eAAe,mBAAqC;GACvE,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;IACH,iBAAiB,EAAE,SAAS,MAAM;IAClC,cAAc;KAAE,GAAG,gBAAgB;KAAc,GAAG,mBAAmB;KAAc,SAAS;IAAK;GACrG,CAAC;EACH;EACA,MAAM,YAAY,eAAe,mBAAqC;GACpE,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;GACL,CAAC;EACH;EACA;EACA;EACA;EACA;CACF;AACF;;;;AAKA,MAAa,4BAA4B;CACvC,oBAAoB;CACpB,YAAY,CAAC;CACb,UAAU,CAAC;AACb"}
@@ -1,8 +1,8 @@
1
1
  import { i as suppressMutationAudit } from "../explicit-activity-scope-DikJ7NAE.js";
2
2
  import "../activity/index.js";
3
3
  import { i as UsageMetricType } from "../usage-BK7eyP42.js";
4
- import { a as resolveAssistantSession, i as isTrackedActorType, l as AI_ASSISTANT_ACTOR_ORIGIN, n as UnifiedTrackerStub, o as trackOperation, r as createProductTracker, s as trackerStub, t as UNIFIED_TRACKER_CONSTANTS } from "../stub-DZ332ZHG.js";
5
- import { i as trackAgentActivity, n as AGENT_ACTIVITY_ACTIONS, r as AGENT_ACTIVITY_RESOURCE_TYPE, t as TrackerModule } from "../tracker-DE4MDVTr.js";
4
+ import { a as resolveAssistantSession, i as isTrackedActorType, l as AI_ASSISTANT_ACTOR_ORIGIN, n as UnifiedTrackerStub, o as trackOperation, r as createProductTracker, s as trackerStub, t as UNIFIED_TRACKER_CONSTANTS } from "../stub-DNkzpQvR.js";
5
+ import { i as trackAgentActivity, n as AGENT_ACTIVITY_ACTIONS, r as AGENT_ACTIVITY_RESOURCE_TYPE, t as TrackerModule } from "../tracker-CDVYIoCb.js";
6
6
 
7
7
  export { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, AI_ASSISTANT_ACTOR_ORIGIN, TrackerModule, UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, UsageMetricType, createProductTracker, isTrackedActorType, resolveAssistantSession, suppressMutationAudit, trackAgentActivity, trackOperation, trackerStub };
8
8
  //# sourceMappingURL=index.js.map