@burdenoff/be-sdk 2026.718.2 → 2026.721.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { withWorkspaceContextSync, withWorkspaceContext, setWorkspaceContext, maybeTagConnection, maybeSetRlsGuc, injectWhereWorkspaceId, getWorkspaceContext, addWorkspaceExtension } from './chunk-MXLCLLCI.js';
2
- import { isTransientAcquireError, installAcquireRetry, ensureServiceApplicationName, createPrismaClient, createPrismaAdapter, createConnectionPool, configurePrismaLogging, PrismaClientWrapper, addGraphExtension } from './chunk-NJ5GTICM.js';
2
+ import { isTransientAcquireError, installAcquireRetry, ensureServiceApplicationName, createPrismaClient, createPrismaAdapter, createConnectionPool, configurePrismaLogging, PrismaClientWrapper, addGraphExtension } from './chunk-EB2I22WV.js';
3
3
  import { getGraphEventEmitter } from './chunk-URDYOM2L.js';
4
4
  import { logger } from './chunk-CBZNP6RF.js';
5
5
  import { __export, __name } from './chunk-XE4OXN2W.js';
@@ -659,5 +659,5 @@ function createContextFromSDK(sdkContext) {
659
659
  __name(createContextFromSDK, "createContextFromSDK");
660
660
 
661
661
  export { buildContextWhereClause, buildContextWhereConditions, checkDatabaseHealth, contextMatches, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, extractFieldsFromModel, getAllModelNames, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, hasModel, initializeDatabase, initializeDatabaseWithConfig, isDatabaseInitialized, loadGeneratedFields, mergeContext, parseContext, prisma_exports, resetDatabaseManager, resolvePoolTuningFromEnv, testConnection, toContextJson };
662
- //# sourceMappingURL=chunk-EQHHYSOE.js.map
663
- //# sourceMappingURL=chunk-EQHHYSOE.js.map
662
+ //# sourceMappingURL=chunk-MGACVHM7.js.map
663
+ //# sourceMappingURL=chunk-MGACVHM7.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/prisma/index.ts","../src/prisma/factory.ts","../src/prisma/manager.ts","../src/prisma/health.ts","../src/prisma/fields.ts","../src/prisma/context.ts"],"names":["resolveWorkspaceExtensionDefault","productName","explicit","process","env","layer","toLowerCase","name","startsWith","createDatabaseClient","PrismaClientConstructor","config","enableGraphExtension","graphEventEmitter","enableWorkspaceExtension","workspaceExtensionConfig","registerShutdownHandlers","prismaConfig","prismaConfigWithDefaults","applicationName","ensureServiceApplicationName","wrapper","createPrismaClient","baseClient","getClient","extendedClient","eventEmitter","getGraphEventEmitter","graphConfig","enabled","addGraphExtension","logger","info","addWorkspaceExtension","db","debug","connect","retries","delay","disconnect","parsePositiveIntEnv","raw","trim","undefined","parsed","Number","parseInt","isFinite","resolvePoolTuningFromEnv","tuning","statementTimeout","statementTimeoutMillis","idleInTransactionTimeout","idleInTransactionTimeoutMillis","lockTimeout","lockTimeoutMillis","createDatabaseClientFromEnv","overrides","databaseUrl","Error","isDevelopment","maxConnections","idleTimeoutMillis","connectionTimeoutMillis","enableQueryLogging","slowQueryThreshold","acquireRetriesRaw","acquireRetries","acquireRetryDelay","acquireRetryDelayMillis","state","initialized","client","initializeDatabase","initializeDatabaseWithConfig","getDb","getDatabaseManager","isDatabaseInitialized","getDatabaseProductName","resetDatabaseManager","error","warn","checkDatabaseHealth","start","Date","now","$queryRaw","latency","healthy","errorMessage","message","String","testConnection","getDatabaseVersion","result","version","getDatabaseStats","health","Promise","all","timestamp","requireFn","createRequire","url","loadGeneratedFields","generatedFieldsPath","generated","default","path","extractFieldsFromModel","modelName","modelFieldsMap","options","modelFields","Object","keys","join","excludeFields","includeRelations","customFilter","fields","relations","excluded","length","filter","field","includes","push","fieldName","isRelation","shouldInclude","type","metadata","totalFields","excludedCount","excludedFields","relationFields","getModelFields","hasModel","getAllModelNames","buildContextWhereClause","contextFilter","conditions","workspaceId","equals","userId","projectId","appId","productId","organizationId","buildContextWhereConditions","context","toContextJson","contextInput","custom","filterNullValues","obj","filtered","key","value","entries","mergeContextField","merged","fieldValue","mergeContext","existingCont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BgBwB,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA","file":"chunk-EQHHYSOE.js","sourcesContent":["/**\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","/**\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 /** 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_STATEMENT_TIMEOUT: server-side statement_timeout in ms (opt-in)\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 server-enforced timeouts).\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 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_STATEMENT_TIMEOUT / DATABASE_IDLE_IN_TRANSACTION_TIMEOUT / DATABASE_LOCK_TIMEOUT:\n * opt-in server-side timeouts in ms (default: OFF, preserving current behavior)\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\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 * 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): Array<{ context: PrismaJsonFilter }> {\n if (!contextFilter) {\n return [];\n }\n\n const conditions: Array<{ context: PrismaJsonFilter }> = [];\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 conditions.push({\n context: {\n path: ['productId'],\n equals: contextFilter.productId,\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 if (filter.productId != null && 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"]}
1
+ {"version":3,"sources":["../src/prisma/index.ts","../src/prisma/factory.ts","../src/prisma/manager.ts","../src/prisma/health.ts","../src/prisma/fields.ts","../src/prisma/context.ts"],"names":["resolveWorkspaceExtensionDefault","productName","explicit","process","env","layer","toLowerCase","name","startsWith","createDatabaseClient","PrismaClientConstructor","config","enableGraphExtension","graphEventEmitter","enableWorkspaceExtension","workspaceExtensionConfig","registerShutdownHandlers","prismaConfig","prismaConfigWithDefaults","applicationName","ensureServiceApplicationName","wrapper","createPrismaClient","baseClient","getClient","extendedClient","eventEmitter","getGraphEventEmitter","graphConfig","enabled","addGraphExtension","logger","info","addWorkspaceExtension","db","debug","connect","retries","delay","disconnect","parsePositiveIntEnv","raw","trim","undefined","parsed","Number","parseInt","isFinite","resolvePoolTuningFromEnv","tuning","statementTimeout","statementTimeoutMillis","idleInTransactionTimeout","idleInTransactionTimeoutMillis","lockTimeout","lockTimeoutMillis","createDatabaseClientFromEnv","overrides","databaseUrl","Error","isDevelopment","maxConnections","idleTimeoutMillis","connectionTimeoutMillis","enableQueryLogging","slowQueryThreshold","acquireRetriesRaw","acquireRetries","acquireRetryDelay","acquireRetryDelayMillis","state","initialized","client","initializeDatabase","initializeDatabaseWithConfig","getDb","getDatabaseManager","isDatabaseInitialized","getDatabaseProductName","resetDatabaseManager","error","warn","checkDatabaseHealth","start","Date","now","$queryRaw","latency","healthy","errorMessage","message","String","testConnection","getDatabaseVersion","result","version","getDatabaseStats","health","Promise","all","timestamp","requireFn","createRequire","url","loadGeneratedFields","generatedFieldsPath","generated","default","path","extractFieldsFromModel","modelName","modelFieldsMap","options","modelFields","Object","keys","join","excludeFields","includeRelations","customFilter","fields","relations","excluded","length","filter","field","includes","push","fieldName","isRelation","shouldInclude","type","metadata","totalFields","excludedCount","excludedFields","relationFields","getModelFields","hasModel","getAllModelNames","buildContextWhereClause","contextFilter","conditions","workspaceId","equals","userId","projectId","appId","productId","organizationId","buildContextWhereConditions","context","toContextJson","contextInput","custom","filterNullValues","obj","filtered","key","value","entries","mergeContextField","merged","fieldValue","mergeContext","existingContext","newContext","Array","isArray","parseContext","contextJson","ctx","contextMatches","createContextFromSDK","sdkContext"],"mappings":";;;;;;;;AAAA,IAAA,cAAA,GAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC8GA,SAASA,iCAAiCC,WAAAA,EAAmB;AAC3D,EAAA,MAAMC,QAAAA,GAAWC,OAAAA,CAAQC,GAAAA,CAAI,6BA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,EAAW;AACtE,IAAA,OAAO,KAAA;AACT,EAAA;AACA,EAAA,IAAItB,OAAOuB,KAAAA,IAAS,IAAA,IAAQI,OAAAA,CAAQJ,KAAAA,KAAUvB,OAAOuB,KAAAA,EAAO;AAC1D,IAAA,OAAO,KAAA;AACT,EAAA;AACA,EAAA,IAAIvB,OAAOwB,SAAAA,IAAa,IAAA,IAAQG,OAAAA,CAAQH,SAAAA,KAAcxB,OAAOwB,SAAAA,EAAW;AACtE,IAAA,OAAO,KAAA;AACT,EAAA;AACA,EAAA,IAAIxB,OAAOyB,cAAAA,IAAkB,IAAA,IAAQE,OAAAA,CAAQF,cAAAA,KAAmBzB,OAAOyB,cAAAA,EAAgB;AACrF,IAAA,OAAO,KAAA;AACT,EAAA;AAEA,EAAA,OAAO,IAAA;AACT;AAzBgBuB,MAAAA,CAAAA,cAAAA,EAAAA,gBAAAA,CAAAA;AAiCT,SAASC,qBAAqBC,UAAAA,EAOpC;AACC,EAAA,OAAO;AACL/B,IAAAA,WAAAA,EAAa+B,WAAW/B,WAAAA,IAAe,IAAA;AACvCE,IAAAA,MAAAA,EAAQ6B,WAAW7B,MAAAA,IAAU,IAAA;AAC7BC,IAAAA,SAAAA,EAAW4B,WAAW5B,SAAAA,IAAa,IAAA;AACnCC,IAAAA,KAAAA,EAAO2B,WAAW3B,KAAAA,IAAS,IAAA;AAC3BC,IAAAA,SAAAA,EAAW0B,WAAW1B,SAAAA,IAAa,IAAA;AACnCC,IAAAA,cAAAA,EAAgByB,WAAWzB,cAAAA,IAAkB;AAC/C,GAAA;AACF;AAhBgBwB,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA","file":"chunk-MGACVHM7.js","sourcesContent":["/**\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","/**\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 /** 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_STATEMENT_TIMEOUT: server-side statement_timeout in ms (opt-in)\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 server-enforced timeouts).\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 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_STATEMENT_TIMEOUT / DATABASE_IDLE_IN_TRANSACTION_TIMEOUT / DATABASE_LOCK_TIMEOUT:\n * opt-in server-side timeouts in ms (default: OFF, preserving current behavior)\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\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 * 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): Array<{ context: PrismaJsonFilter }> {\n if (!contextFilter) {\n return [];\n }\n\n const conditions: Array<{ context: PrismaJsonFilter }> = [];\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 conditions.push({\n context: {\n path: ['productId'],\n equals: contextFilter.productId,\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 if (filter.productId != null && 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"]}
@@ -9,7 +9,7 @@ var RESOURCE_CAP_DEFAULTS = {
9
9
  scope: "user"
10
10
  },
11
11
  workspaceMember: {
12
- free: 5,
12
+ free: 8,
13
13
  paidDefault: 500,
14
14
  scope: "workspace"
15
15
  },
@@ -115,13 +115,38 @@ var ResourceCapsModule = class {
115
115
  __name(this, "ResourceCapsModule");
116
116
  }
117
117
  client;
118
+ transport;
118
119
  cacheTtlMs;
119
120
  defaultTier;
121
+ onFallback;
122
+ warnedClientless = false;
120
123
  planCache = /* @__PURE__ */ new Map();
121
124
  constructor(config = {}) {
122
125
  this.client = config.client;
126
+ this.transport = config.transport;
123
127
  this.cacheTtlMs = config.cacheTtlMs ?? 6e4;
124
128
  this.defaultTier = config.defaultTier ?? "free";
129
+ this.onFallback = config.onFallback;
130
+ }
131
+ /**
132
+ * (Re)bind runtime dependencies on an already-constructed module. The SDK
133
+ * bootstrap uses this to prime the process-wide singleton with a billing
134
+ * transport even if an early caller already lazily created it clientless
135
+ * (a bare `getResourceCaps(config)` ignores config once the instance exists).
136
+ * Clears the plan cache so stale fallback entries don't linger.
137
+ */
138
+ configure(config) {
139
+ if (config.client !== void 0) this.client = config.client;
140
+ if (config.transport !== void 0) this.transport = config.transport;
141
+ if (config.onFallback !== void 0) this.onFallback = config.onFallback;
142
+ if (typeof config.cacheTtlMs === "number") this.cacheTtlMs = config.cacheTtlMs;
143
+ if (config.defaultTier) this.defaultTier = config.defaultTier;
144
+ if (this.hasBillingSource()) this.warnedClientless = false;
145
+ this.planCache.clear();
146
+ }
147
+ /** True when the module can actually reach billing (has a transport or client). */
148
+ hasBillingSource() {
149
+ return Boolean(this.transport || this.client);
125
150
  }
126
151
  /**
127
152
  * Resolve the cap for a given resource for the supplied user.
@@ -192,14 +217,12 @@ var ResourceCapsModule = class {
192
217
  return plan;
193
218
  }
194
219
  async fetchPlan(userId) {
195
- if (!this.client) {
220
+ if (!this.hasBillingSource()) {
221
+ this.warnClientlessOnce();
196
222
  return this.fallbackPlan();
197
223
  }
198
224
  try {
199
- const res = await this.client.query(PLAN_QUERY, {
200
- userId
201
- });
202
- const planNode = res?.userBillingPlan;
225
+ const planNode = await this.fetchPlanNode(userId);
203
226
  if (!planNode) {
204
227
  return this.fallbackPlan();
205
228
  }
@@ -219,6 +242,32 @@ var ResourceCapsModule = class {
219
242
  return this.fallbackPlan();
220
243
  }
221
244
  }
245
+ /**
246
+ * Resolve the raw `userBillingPlan` node via the injected transport (preferred)
247
+ * or the legacy direct client. Guarded by {@link hasBillingSource} in the
248
+ * caller, so at least one path is present here.
249
+ */
250
+ async fetchPlanNode(userId) {
251
+ if (this.transport) {
252
+ const data = await this.transport(PLAN_QUERY, {
253
+ userId
254
+ });
255
+ return data?.userBillingPlan ?? null;
256
+ }
257
+ if (this.client) {
258
+ const res = await this.client.query(PLAN_QUERY, {
259
+ userId
260
+ });
261
+ return res?.userBillingPlan ?? null;
262
+ }
263
+ return null;
264
+ }
265
+ warnClientlessOnce() {
266
+ if (this.warnedClientless) return;
267
+ this.warnedClientless = true;
268
+ logger.warn("resource-caps: running WITHOUT a billing transport/client \u2014 every resource cap will use the free-tier fallback regardless of the customer plan. Ensure initializeBurdenoffSDK() ran with a layer/gateway configured (BOFF-4805).");
269
+ this.onFallback?.();
270
+ }
222
271
  fallbackPlan() {
223
272
  return {
224
273
  planName: this.defaultTier === "paid" ? "fallback-paid" : "fallback-free",
@@ -253,15 +302,23 @@ var defaultInstance = null;
253
302
  function getResourceCaps(config) {
254
303
  if (!defaultInstance) {
255
304
  defaultInstance = new ResourceCapsModule(config);
305
+ } else if (config) {
306
+ defaultInstance.configure(config);
256
307
  }
257
308
  return defaultInstance;
258
309
  }
259
310
  __name(getResourceCaps, "getResourceCaps");
311
+ function configureResourceCaps(config) {
312
+ const instance = getResourceCaps();
313
+ instance.configure(config);
314
+ return instance;
315
+ }
316
+ __name(configureResourceCaps, "configureResourceCaps");
260
317
  function __resetResourceCapsForTests() {
261
318
  defaultInstance = null;
262
319
  }
263
320
  __name(__resetResourceCapsForTests, "__resetResourceCapsForTests");
264
321
 
265
- export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, __resetResourceCapsForTests, getResourceCaps };
266
- //# sourceMappingURL=chunk-VDDOGIWY.js.map
267
- //# sourceMappingURL=chunk-VDDOGIWY.js.map
322
+ export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, __resetResourceCapsForTests, configureResourceCaps, getResourceCaps };
323
+ //# sourceMappingURL=chunk-PCQQHC2Z.js.map
324
+ //# sourceMappingURL=chunk-PCQQHC2Z.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/resource-caps/index.ts"],"names":["RESOURCE_CAP_DEFAULTS","workspace","free","paidDefault","scope","workspaceMember","sandbox","vibe","agent","conversation","message","tag","file","group","calendar","scheduledTask","form","apiKey","webhook","ResourceCapExceededError","GraphQLError","detail","resource","currentCount","limit","planName","extensions","code","userMessage","technicalMessage","name","PLAN_QUERY","ResourceCapsModule","client","transport","cacheTtlMs","defaultTier","onFallback","warnedClientless","planCache","Map","config","configure","undefined","hasBillingSource","clear","Boolean","getResourceCap","userId","Error","defaults","plan","resolvePlan","override","overrides","planTier","isFallback","enforceResourceCap","cap","invalidate","delete","invalidateAll","cached","get","Date","now","fetchedAt","fetchPlan","set","warnClientlessOnce","fallbackPlan","planNode","fetchPlanNode","tier","normaliseTier","sanitizeOverrides","resourceCaps","err","logger","warn","data","userBillingPlan","res","query","raw","fallback","lc","toLowerCase","out","key","value","Object","entries","Number","isFinite","Math","max","floor","defaultInstance","getResourceCaps","configureResourceCaps","instance","__resetResourceCapsForTests"],"mappings":";;;;AAiEO,IAAMA,qBAAAA,GAAmE;EAC9EC,SAAAA,EAAW;IAAEC,IAAAA,EAAM,CAAA;IAAGC,WAAAA,EAAa,EAAA;IAAIC,KAAAA,EAAO;AAAO,GAAA;EACrDC,eAAAA,EAAiB;IAAEH,IAAAA,EAAM,CAAA;IAAGC,WAAAA,EAAa,GAAA;IAAKC,KAAAA,EAAO;AAAY,GAAA;EACjEE,OAAAA,EAAS;IAAEJ,IAAAA,EAAM,CAAA;IAAGC,WAAAA,EAAa,EAAA;IAAIC,KAAAA,EAAO;AAAO,GAAA;EACnDG,IAAAA,EAAM;IAAEL,IAAAA,EAAM,EAAA;IAAIC,WAAAA,EAAa,GAAA;IAAKC,KAAAA,EAAO;AAAO,GAAA;EAClDI,KAAAA,EAAO;IAAEN,IAAAA,EAAM,CAAA;IAAGC,WAAAA,EAAa,EAAA;IAAIC,KAAAA,EAAO;AAAY,GAAA;EACtDK,YAAAA,EAAc;IAAEP,IAAAA,EAAM,EAAA;IAAIC,WAAAA,EAAa,GAAA;IAAMC,KAAAA,EAAO;AAAW,GAAA;EAC/DM,OAAAA,EAAS;IAAER,IAAAA,EAAM,GAAA;IAAKC,WAAAA,EAAa,GAAA;IAAOC,KAAAA,EAAO;AAAW,G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,CAAAA;AAeT,IAAIuB,eAAAA,GAA6C,IAAA;AAM1C,SAASC,gBAAgB1D,MAAAA,EAA2B;AACzD,EAAA,IAAI,CAACyD,eAAAA,EAAiB;AACpBA,IAAAA,eAAAA,GAAkB,IAAIlE,mBAAmBS,MAAAA,CAAAA;AAC3C,EAAA,CAAA,MAAA,IAAWA,MAAAA,EAAQ;AAIjByD,IAAAA,eAAAA,CAAgBxD,UAAUD,MAAAA,CAAAA;AAC5B,EAAA;AACA,EAAA,OAAOyD,eAAAA;AACT;AAVgBC,MAAAA,CAAAA,eAAAA,EAAAA,iBAAAA,CAAAA;AAkBT,SAASC,sBAAsB3D,MAAAA,EAA0B;AAC9D,EAAA,MAAM4D,WAAWF,eAAAA,EAAAA;AACjBE,EAAAA,QAAAA,CAAS3D,UAAUD,MAAAA,CAAAA;AACnB,EAAA,OAAO4D,QAAAA;AACT;AAJgBD,MAAAA,CAAAA,qBAAAA,EAAAA,uBAAAA,CAAAA;AAOT,SAASE,2BAAAA,GAAAA;AACdJ,EAAAA,eAAAA,GAAkB,IAAA;AACpB;AAFgBI,MAAAA,CAAAA,2BAAAA,EAAAA,6BAAAA,CAAAA","file":"chunk-PCQQHC2Z.js","sourcesContent":["/**\n * Resource Caps Module\n *\n * Enforces per-user / per-workspace resource ceilings to prevent unbounded\n * resource use on a multi-tenant SaaS. Caps come from the user's billing plan\n * (resolved via global-billing-svc) and fall back to static defaults defined\n * here when the plan lookup fails or the resource isn't overridden.\n *\n * Two plan tiers exist by default:\n * - free: tight per-user / per-workspace ceilings\n * - paid (default): ~100x looser; individual paid plans can override via the\n * `Plan.resourceCaps` JSON column in global-billing-svc.\n *\n * @example\n * ```ts\n * import { resourceCaps } from '@burdenoff/be-sdk/resource-caps';\n *\n * const { limit } = await resourceCaps.getResourceCap(userId, 'tag');\n * await resourceCaps.enforceResourceCap(userId, 'tag', currentCount);\n * ```\n */\n\nimport { GraphQLError } from 'graphql';\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport { logger } from '../logger/index.js';\n\n// ---------------------------------------------------------------------------\n// Resource registry\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical resource names. Adding a new capped resource? Append it here,\n * extend RESOURCE_CAP_DEFAULTS, and reference it from the relevant svc.\n */\nexport type ResourceName =\n | 'workspace' // per user\n | 'workspaceMember' // per workspace\n | 'sandbox' // per user\n | 'vibe' // per user\n | 'agent' // per workspace\n | 'conversation' // per user/day\n | 'message' // per user/day\n | 'tag' // per workspace\n | 'file' // per user (count only)\n | 'group' // per workspace\n | 'calendar' // per user\n | 'scheduledTask' // per user\n | 'form' // per user\n | 'apiKey' // per user\n | 'webhook'; // per workspace\n\nexport type PlanTier = 'free' | 'paid';\n\nexport interface ResourceCapDefaults {\n free: number;\n paidDefault: number;\n /** Optional scope hint used by callers when wiring guards */\n scope: 'user' | 'workspace' | 'user/day';\n}\n\n/**\n * Static fallback caps. Real values may be overridden per plan in\n * global-billing-svc Plan.resourceCaps JSON.\n */\nexport const RESOURCE_CAP_DEFAULTS: Record<ResourceName, ResourceCapDefaults> = {\n workspace: { free: 3, paidDefault: 50, scope: 'user' },\n workspaceMember: { free: 8, paidDefault: 500, scope: 'workspace' },\n sandbox: { free: 2, paidDefault: 50, scope: 'user' },\n vibe: { free: 10, paidDefault: 500, scope: 'user' },\n agent: { free: 2, paidDefault: 20, scope: 'workspace' },\n conversation: { free: 20, paidDefault: 2000, scope: 'user/day' },\n message: { free: 200, paidDefault: 20000, scope: 'user/day' },\n tag: { free: 50, paidDefault: 5000, scope: 'workspace' },\n file: { free: 100, paidDefault: 10000, scope: 'user' },\n group: { free: 5, paidDefault: 500, scope: 'workspace' },\n calendar: { free: 3, paidDefault: 100, scope: 'user' },\n scheduledTask: { free: 5, paidDefault: 500, scope: 'user' },\n form: { free: 5, paidDefault: 500, scope: 'user' },\n apiKey: { free: 2, paidDefault: 50, scope: 'user' },\n webhook: { free: 2, paidDefault: 100, scope: 'workspace' },\n};\n\n// ---------------------------------------------------------------------------\n// Types & errors\n// ---------------------------------------------------------------------------\n\nexport interface ResourceCap {\n resource: ResourceName;\n limit: number;\n planName: string;\n planTier: PlanTier;\n /** True when the cap came from defaults, not from the billing service */\n isFallback: boolean;\n}\n\n/**\n * Layer-aware transport for the `userBillingPlan` lookup. Given the GraphQL\n * document + variables, returns the response `data` object (or null). Preferred\n * over `client`: the SDK bootstrap wires this to a same-layer (global) or\n * cross-layer (wspace→global) gateway call so billing is reachable from every\n * service without any per-call-site wiring (BOFF-4805).\n */\nexport type BillingPlanTransport = (query: string, variables: Record<string, unknown>) => Promise<unknown>;\n\nexport interface ResourceCapsConfig {\n client?: BurdenoffGraphQLClient;\n /** Preferred billing lookup path; see {@link BillingPlanTransport}. */\n transport?: BillingPlanTransport;\n /** Optional in-memory TTL for plan lookups; defaults to 60s */\n cacheTtlMs?: number;\n /** Default plan tier when billing lookup fails */\n defaultTier?: PlanTier;\n /**\n * Telemetry hook invoked when the module cannot reach billing (no transport /\n * client) and collapses to the free-tier fallback. Wired to a metric counter\n * by observability so an unwired/broken integration is visible (BOFF-4809).\n */\n onFallback?: () => void;\n}\n\ninterface CachedPlan {\n planName: string;\n planTier: PlanTier;\n overrides: Partial<Record<ResourceName, number>>;\n fetchedAt: number;\n}\n\n/**\n * Thrown when an entity create operation would push the user past the cap.\n * The matching GraphQL error has extensions.code = RESOURCE_CAP_EXCEEDED\n * so clients can detect and route to an upgrade flow.\n */\nexport class ResourceCapExceededError extends GraphQLError {\n constructor(detail: { resource: ResourceName; currentCount: number; limit: number; planName: string }) {\n super(\n `Resource cap exceeded for ${detail.resource}: ${detail.currentCount}/${detail.limit} on plan '${detail.planName}'.`,\n {\n extensions: {\n code: 'RESOURCE_CAP_EXCEEDED',\n userMessage: \"You've reached your plan limit. Upgrade your plan to continue.\",\n technicalMessage: `Resource cap exceeded for ${detail.resource}: ${detail.currentCount}/${detail.limit} on plan '${detail.planName}'.`,\n resource: detail.resource,\n currentCount: detail.currentCount,\n limit: detail.limit,\n planName: detail.planName,\n },\n }\n );\n this.name = 'ResourceCapExceededError';\n }\n}\n\n// ---------------------------------------------------------------------------\n// Module\n// ---------------------------------------------------------------------------\n\nconst PLAN_QUERY = /* GraphQL */ `\n query GetUserPlanForCaps($userId: ID!) {\n userBillingPlan(userId: $userId) {\n planName\n tier\n resourceCaps\n }\n }\n`;\n\ninterface PlanQueryResponse {\n userBillingPlan?: {\n planName?: string | null;\n tier?: string | null;\n resourceCaps?: Record<string, number> | null;\n } | null;\n}\n\ntype PlanNode = NonNullable<PlanQueryResponse['userBillingPlan']>;\n\nexport class ResourceCapsModule {\n private client?: BurdenoffGraphQLClient;\n private transport?: BillingPlanTransport;\n private cacheTtlMs: number;\n private defaultTier: PlanTier;\n private onFallback?: () => void;\n private warnedClientless = false;\n private readonly planCache = new Map<string, CachedPlan>();\n\n constructor(config: ResourceCapsConfig = {}) {\n this.client = config.client;\n this.transport = config.transport;\n this.cacheTtlMs = config.cacheTtlMs ?? 60_000;\n this.defaultTier = config.defaultTier ?? 'free';\n this.onFallback = config.onFallback;\n }\n\n /**\n * (Re)bind runtime dependencies on an already-constructed module. The SDK\n * bootstrap uses this to prime the process-wide singleton with a billing\n * transport even if an early caller already lazily created it clientless\n * (a bare `getResourceCaps(config)` ignores config once the instance exists).\n * Clears the plan cache so stale fallback entries don't linger.\n */\n configure(config: ResourceCapsConfig): void {\n if (config.client !== undefined) this.client = config.client;\n if (config.transport !== undefined) this.transport = config.transport;\n if (config.onFallback !== undefined) this.onFallback = config.onFallback;\n if (typeof config.cacheTtlMs === 'number') this.cacheTtlMs = config.cacheTtlMs;\n if (config.defaultTier) this.defaultTier = config.defaultTier;\n if (this.hasBillingSource()) this.warnedClientless = false;\n this.planCache.clear();\n }\n\n /** True when the module can actually reach billing (has a transport or client). */\n hasBillingSource(): boolean {\n return Boolean(this.transport || this.client);\n }\n\n /**\n * Resolve the cap for a given resource for the supplied user.\n * Order: plan-override → plan-tier-default → static free default.\n */\n async getResourceCap(userId: string, resource: ResourceName): Promise<ResourceCap> {\n if (!userId) {\n throw new Error('getResourceCap: userId is required');\n }\n const defaults = RESOURCE_CAP_DEFAULTS[resource];\n if (!defaults) {\n throw new Error(`getResourceCap: unknown resource '${resource}'`);\n }\n\n const plan = await this.resolvePlan(userId);\n const override = plan.overrides[resource];\n if (typeof override === 'number' && override >= 0) {\n return {\n resource,\n limit: override,\n planName: plan.planName,\n planTier: plan.planTier,\n isFallback: false,\n };\n }\n\n const limit = plan.planTier === 'paid' ? defaults.paidDefault : defaults.free;\n return {\n resource,\n limit,\n planName: plan.planName,\n planTier: plan.planTier,\n isFallback: plan.planName === 'fallback-free' || plan.planName === 'fallback-paid',\n };\n }\n\n /**\n * Throws ResourceCapExceededError when currentCount >= limit.\n * Use BEFORE the create transaction to avoid orphan rows.\n */\n async enforceResourceCap(userId: string, resource: ResourceName, currentCount: number): Promise<ResourceCap> {\n const cap = await this.getResourceCap(userId, resource);\n if (currentCount >= cap.limit) {\n throw new ResourceCapExceededError({\n resource,\n currentCount,\n limit: cap.limit,\n planName: cap.planName,\n });\n }\n return cap;\n }\n\n /** Invalidate cache for a user (e.g. after plan upgrade) */\n invalidate(userId: string): void {\n this.planCache.delete(userId);\n }\n\n /** Clear entire plan cache */\n invalidateAll(): void {\n this.planCache.clear();\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private async resolvePlan(userId: string): Promise<CachedPlan> {\n const cached = this.planCache.get(userId);\n if (cached && Date.now() - cached.fetchedAt < this.cacheTtlMs) {\n return cached;\n }\n\n const plan = await this.fetchPlan(userId);\n this.planCache.set(userId, plan);\n return plan;\n }\n\n private async fetchPlan(userId: string): Promise<CachedPlan> {\n // No billing source wired → every cap silently collapses to the free-tier\n // fallback regardless of the customer's plan. Warn loudly (once) so an\n // unwired/broken integration can't hide in prod (BOFF-4805).\n if (!this.hasBillingSource()) {\n this.warnClientlessOnce();\n return this.fallbackPlan();\n }\n try {\n const planNode = await this.fetchPlanNode(userId);\n if (!planNode) {\n return this.fallbackPlan();\n }\n const tier = normaliseTier(planNode.tier, this.defaultTier);\n const overrides = sanitizeOverrides(planNode.resourceCaps);\n return {\n planName: planNode.planName ?? (tier === 'paid' ? 'paid' : 'free'),\n planTier: tier,\n overrides,\n fetchedAt: Date.now(),\n };\n } catch (err) {\n logger.warn('resource-caps: plan lookup failed; falling back to default tier', {\n err,\n userId,\n });\n return this.fallbackPlan();\n }\n }\n\n /**\n * Resolve the raw `userBillingPlan` node via the injected transport (preferred)\n * or the legacy direct client. Guarded by {@link hasBillingSource} in the\n * caller, so at least one path is present here.\n */\n private async fetchPlanNode(userId: string): Promise<PlanNode | null> {\n if (this.transport) {\n const data = (await this.transport(PLAN_QUERY, { userId })) as PlanQueryResponse | null | undefined;\n return data?.userBillingPlan ?? null;\n }\n if (this.client) {\n const res = await this.client.query<PlanQueryResponse>(PLAN_QUERY, { userId });\n return res?.userBillingPlan ?? null;\n }\n return null;\n }\n\n private warnClientlessOnce(): void {\n if (this.warnedClientless) return;\n this.warnedClientless = true;\n logger.warn(\n 'resource-caps: running WITHOUT a billing transport/client — every resource cap will use the ' +\n 'free-tier fallback regardless of the customer plan. Ensure initializeBurdenoffSDK() ran with a ' +\n 'layer/gateway configured (BOFF-4805).'\n );\n this.onFallback?.();\n }\n\n private fallbackPlan(): CachedPlan {\n return {\n planName: this.defaultTier === 'paid' ? 'fallback-paid' : 'fallback-free',\n planTier: this.defaultTier,\n overrides: {},\n fetchedAt: Date.now(),\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction normaliseTier(raw: string | null | undefined, fallback: PlanTier): PlanTier {\n if (!raw) return fallback;\n const lc = raw.toLowerCase();\n if (lc === 'free' || lc === 'paid') return lc;\n // Treat anything non-free as paid (enterprise, business, pro, etc.)\n if (lc === 'enterprise' || lc === 'business' || lc === 'pro' || lc === 'team') {\n return 'paid';\n }\n return fallback;\n}\n\nfunction sanitizeOverrides(raw: Record<string, number> | null | undefined): Partial<Record<ResourceName, number>> {\n if (!raw || typeof raw !== 'object') return {};\n const out: Partial<Record<ResourceName, number>> = {};\n for (const [key, value] of Object.entries(raw)) {\n if (key in RESOURCE_CAP_DEFAULTS && typeof value === 'number' && Number.isFinite(value)) {\n out[key as ResourceName] = Math.max(0, Math.floor(value));\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Convenience singleton\n// ---------------------------------------------------------------------------\n\nlet defaultInstance: ResourceCapsModule | null = null;\n\n/**\n * Obtain a process-wide singleton. The first call binds the GraphQL client\n * (typically the SDK's internal client). Later calls return the same instance.\n */\nexport function getResourceCaps(config?: ResourceCapsConfig): ResourceCapsModule {\n if (!defaultInstance) {\n defaultInstance = new ResourceCapsModule(config);\n } else if (config) {\n // Previously the config was silently dropped once the singleton existed —\n // the root cause of BOFF-4805 where the billing client could never be bound\n // after a lazy first construction. Apply it instead.\n defaultInstance.configure(config);\n }\n return defaultInstance;\n}\n\n/**\n * Prime/rebind the process-wide singleton with billing connectivity. Call once\n * during SDK bootstrap. Unlike a bare `getResourceCaps(config)` on a fresh\n * process, this is explicit about the intent to (re)wire and is safe to call\n * after the singleton was already lazily created clientless.\n */\nexport function configureResourceCaps(config: ResourceCapsConfig): ResourceCapsModule {\n const instance = getResourceCaps();\n instance.configure(config);\n return instance;\n}\n\n/** Reset the singleton (for tests) */\nexport function __resetResourceCapsForTests(): void {\n defaultInstance = null;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { security_exports } from './chunk-KKJPFKO5.js';
2
- import { LayerManager } from './chunk-7UJXIX4I.js';
3
2
  import { signServiceJwt } from './chunk-VFCMR5GX.js';
4
3
  import { ContextManager } from './chunk-RZOFS2BQ.js';
4
+ import { LayerManager } from './chunk-7UJXIX4I.js';
5
5
  import { DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG } from './chunk-YFOHAHZE.js';
6
6
  import { logger } from './chunk-CBZNP6RF.js';
7
7
  import { __export, __name } from './chunk-XE4OXN2W.js';
@@ -522,5 +522,5 @@ function createGatewayClientFromEnv() {
522
522
  __name(createGatewayClientFromEnv, "createGatewayClientFromEnv");
523
523
 
524
524
  export { CircuitState, GatewayClient, GatewayError, GatewayErrorType, createGatewayClient, createGatewayClientFromEnv, gateway_exports };
525
- //# sourceMappingURL=chunk-U77L54IQ.js.map
526
- //# sourceMappingURL=chunk-U77L54IQ.js.map
525
+ //# sourceMappingURL=chunk-VLNLOFB3.js.map
526
+ //# sourceMappingURL=chunk-VLNLOFB3.js.map