@burdenoff/be-sdk 2026.1128.1 → 2026.1128.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/activity/index.d.ts +2 -2
- package/dist/auth/index.d.ts +1 -1
- package/dist/bootstrap/index.d.ts +1 -1
- package/dist/bootstrap/index.js.map +1 -1
- package/dist/context/index.d.ts +3 -2
- package/dist/context/index.js +100 -72
- package/dist/context/index.js.map +1 -1
- package/dist/event-queue/index.d.ts +1 -1
- package/dist/feature-flags/index.d.ts +1 -1
- package/dist/graph/index.d.ts +1 -1
- package/dist/{graphql-C8jKLLel.d.ts → graphql-DcZAKC6p.d.ts} +1 -1
- package/dist/{index-tLd9b-nS.d.ts → index-B-yXdMeb.d.ts} +2 -2
- package/dist/{index-CkB68nQA.d.ts → index-B4ckqUZX.d.ts} +1 -1
- package/dist/{index-jStzN9rq.d.ts → index-BmL-JjQK.d.ts} +1 -1
- package/dist/{index-Dw_0wE4q.d.ts → index-C96mNrLW.d.ts} +2 -2
- package/dist/{index-B1bHk4Rq.d.ts → index-CGPNFIR3.d.ts} +2 -2
- package/dist/{index-BTaQMEgB.d.ts → index-CQ3vxT5P.d.ts} +6 -1
- package/dist/{index-KlrnELrN.d.ts → index-CZWopQsh.d.ts} +1 -1
- package/dist/{index-Cl2L2P47.d.ts → index-Cs426iRP.d.ts} +4 -4
- package/dist/{index-BQ5O967l.d.ts → index-Cx3z-7T1.d.ts} +3 -3
- package/dist/{index-CIayzveI.d.ts → index-DYKWUbL4.d.ts} +3 -3
- package/dist/{index-C_WEvMzP.d.ts → index-UQSbAERe.d.ts} +2 -2
- package/dist/{index-12NbzOYy.d.ts → index-cPPtZTJh.d.ts} +1 -1
- package/dist/{index-DS-tPMFi.d.ts → index-j1B6eYHc.d.ts} +2 -2
- package/dist/index.d.ts +14 -14
- package/dist/index.js +1 -1
- package/dist/instrumentation/index.d.ts +2 -2
- package/dist/logger/index.d.ts +1 -1
- package/dist/notifications/index.d.ts +1 -1
- package/dist/payments/index.d.ts +2 -2
- package/dist/prisma/index.d.ts +2 -2
- package/dist/rbac/index.d.ts +1 -1
- package/dist/resource-caps/index.d.ts +1 -1
- package/dist/search/index.d.ts +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +30 -3
- package/dist/server/index.js.map +1 -1
- package/dist/telemetry/index.d.ts +2 -2
- package/dist/tracker/index.d.ts +2 -2
- package/dist/translation/index.d.ts +2 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/types/index.js.map +1 -1
- package/dist/{types-oV9uAkMA.d.ts → types-IXZyPJCR.d.ts} +1 -1
- package/dist/usage/index.d.ts +1 -1
- package/dist/workspace-extension-ByopOwtK.js.map +1 -1
- package/dist/{workspace-extension-DKxDI4H6.d.ts → workspace-extension-C0qib11C.d.ts} +2 -0
- package/package.json +1 -1
package/dist/activity/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as BurdenoffGraphQLClient } from "../graphql-
|
|
2
|
-
import {
|
|
1
|
+
import { t as BurdenoffGraphQLClient } from "../graphql-DcZAKC6p.js";
|
|
2
|
+
import { h as SDKError, m as SDKContext } from "../index-CQ3vxT5P.js";
|
|
3
3
|
export declare enum ActivityType {
|
|
4
4
|
CREATE = "create",
|
|
5
5
|
READ = "read",
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as AuthCookieHelper, i as VerifyTokenResult, n as RefreshTokenResult, o as CookieOptions, r as TokenPayload, t as AuthModule } from "../index-
|
|
1
|
+
import { a as AuthCookieHelper, i as VerifyTokenResult, n as RefreshTokenResult, o as CookieOptions, r as TokenPayload, t as AuthModule } from "../index-Cx3z-7T1.js";
|
|
2
2
|
export { AuthCookieHelper, AuthModule, CookieOptions, RefreshTokenResult, TokenPayload, VerifyTokenResult };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DatabaseConfig } from "../database/index.js";
|
|
2
|
-
import {
|
|
2
|
+
import { m as SDKContext, p as SDKConfig } from "../index-CQ3vxT5P.js";
|
|
3
3
|
type HeaderValue = string | string[] | undefined;
|
|
4
4
|
export interface BootstrapConfig extends SDKConfig {
|
|
5
5
|
database?: DatabaseConfig;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/bootstrap/index.ts"],"sourcesContent":["/**\n * Bootstrap Module\n * Helpers for bootstrapping server, loading modules, and setting up schemas\n */\n\nimport { logger } from '../logger/index.js';\nimport { DatabaseModule, type DatabaseConfig } from '../database/index.js';\nimport { ContextManager } from '../context/index.js';\nimport { disposeAll } from '../lifecycle/index.js';\nimport type { SDKConfig, SDKContext } from '../types/index.js';\n\n/**\n * Type for HTTP header values\n */\ntype HeaderValue = string | string[] | undefined;\n\nexport interface BootstrapConfig extends SDKConfig {\n /** Database configuration */\n database?: DatabaseConfig;\n /** Enable health checks */\n healthCheck?: boolean;\n /** Health check interval in milliseconds */\n healthCheckInterval?: number;\n /** Modules to load */\n modules?: string[];\n /** Environment */\n environment?: 'development' | 'staging' | 'production';\n /** Service name */\n serviceName?: string;\n /** Service version */\n serviceVersion?: string;\n /** Port to run health check server */\n healthCheckPort?: number;\n}\n\nexport interface BootstrapResult {\n success: boolean;\n serviceName: string;\n serviceVersion: string;\n environment: string;\n startedAt: string;\n modules: string[];\n databaseConnected: boolean;\n healthCheckEnabled: boolean;\n}\n\nexport interface BootstrapHealthCheckResult {\n healthy: boolean;\n checks: {\n database?: boolean;\n graphql?: boolean;\n memory?: {\n used: number;\n total: number;\n percentage: number;\n };\n uptime?: number;\n };\n timestamp: string;\n}\n\n/**\n * Bootstrap Module\n */\nexport class BootstrapModule {\n private config: BootstrapConfig;\n private startTime: Date;\n private healthCheckInterval?: NodeJS.Timeout;\n\n constructor(config: BootstrapConfig) {\n this.config = config;\n this.startTime = new Date();\n }\n\n /**\n * Bootstrap the application\n */\n public async bootstrap(): Promise<BootstrapResult> {\n logger.info('[Bootstrap] Starting application bootstrap', {\n serviceName: this.config.serviceName,\n environment: this.config.environment || 'development',\n });\n\n try {\n // 1. Validate configuration\n await this.validateConfiguration();\n\n // 2. Connect to database\n const databaseConnected = await this.connectDatabase();\n\n // 3. Load modules\n const loadedModules = await this.loadModules();\n\n // 4. Setup health checks\n if (this.config.healthCheck) {\n await this.setupHealthChecks();\n }\n\n // 5. Setup signal handlers\n this.setupSignalHandlers();\n\n const result: BootstrapResult = {\n success: true,\n serviceName: this.config.serviceName || 'burdenoff-service',\n serviceVersion: this.config.serviceVersion || '1.0.0',\n environment: this.config.environment || 'development',\n startedAt: this.startTime.toISOString(),\n modules: loadedModules,\n databaseConnected,\n healthCheckEnabled: this.config.healthCheck || false,\n };\n\n logger.info('[Bootstrap] Application bootstrapped successfully', result);\n\n return result;\n } catch (error) {\n logger.error('[Bootstrap] Failed to bootstrap application', { error });\n throw error;\n }\n }\n\n /**\n * Validate configuration\n */\n private async validateConfiguration(): Promise<void> {\n logger.debug('[Bootstrap] Validating configuration');\n\n if (!this.config.workspacesApiUrl) {\n throw new Error('Workspaces API URL is required');\n }\n\n if (this.config.database?.url && !DatabaseModule.validateDatabaseUrl(this.config.database.url)) {\n throw new Error('Invalid database URL');\n }\n\n logger.debug('[Bootstrap] Configuration validated');\n }\n\n /**\n * Connect to database\n */\n private async connectDatabase(): Promise<boolean> {\n if (!this.config.database) {\n logger.debug('[Bootstrap] No database configuration provided, skipping');\n return false;\n }\n\n logger.info('[Bootstrap] Connecting to database');\n\n try {\n // Database connection is typically handled by Prisma or other ORM\n // This is a placeholder for validation and logging\n const sanitizedUrl = DatabaseModule.sanitizeDatabaseUrl(this.config.database.url);\n logger.info('[Bootstrap] Database connection configured', { url: sanitizedUrl });\n\n return true;\n } catch (error) {\n logger.error('[Bootstrap] Failed to connect to database', { error });\n return false;\n }\n }\n\n /**\n * Load modules\n */\n private async loadModules(): Promise<string[]> {\n const modules = this.config.modules || [];\n\n if (modules.length === 0) {\n logger.debug('[Bootstrap] No modules to load');\n return [];\n }\n\n logger.info('[Bootstrap] Loading modules', { modules });\n\n const loadedModules: string[] = [];\n\n for (const moduleName of modules) {\n try {\n logger.debug(`[Bootstrap] Loading module: ${moduleName}`);\n // Module loading logic would go here\n loadedModules.push(moduleName);\n } catch (error) {\n logger.error(`[Bootstrap] Failed to load module: ${moduleName}`, { error });\n }\n }\n\n logger.info('[Bootstrap] Modules loaded', { loaded: loadedModules });\n\n return loadedModules;\n }\n\n /**\n * Setup health checks\n */\n private async setupHealthChecks(): Promise<void> {\n logger.info('[Bootstrap] Setting up health checks');\n\n const interval = this.config.healthCheckInterval || 30000; // 30 seconds\n\n this.healthCheckInterval = setInterval(() => {\n void (async () => {\n const health = await this.performHealthCheck();\n\n if (!health.healthy) {\n logger.warn('[Bootstrap] Health check failed', health);\n } else {\n logger.debug('[Bootstrap] Health check passed', health);\n }\n })();\n }, interval);\n\n logger.info('[Bootstrap] Health checks configured', { interval });\n }\n\n /**\n * Perform health check\n */\n public async performHealthCheck(): Promise<BootstrapHealthCheckResult> {\n const checks: BootstrapHealthCheckResult['checks'] = {};\n\n // Memory check\n const memUsage = process.memoryUsage();\n checks.memory = {\n used: memUsage.heapUsed,\n total: memUsage.heapTotal,\n percentage: (memUsage.heapUsed / memUsage.heapTotal) * 100,\n };\n\n // Uptime\n checks.uptime = Math.floor((Date.now() - this.startTime.getTime()) / 1000);\n\n // Determine overall health\n const healthy =\n checks.memory.percentage < 90 && // Less than 90% memory usage\n checks.uptime > 0;\n\n return {\n healthy,\n checks,\n timestamp: new Date().toISOString(),\n };\n }\n\n /**\n * Setup signal handlers for graceful shutdown\n */\n private setupSignalHandlers(): void {\n logger.debug('[Bootstrap] Setting up signal handlers');\n\n const gracefulShutdown = async (signal: string): Promise<void> => {\n logger.info(`[Bootstrap] Received ${signal}, shutting down gracefully`);\n\n // Clear health check interval\n if (this.healthCheckInterval) {\n clearInterval(this.healthCheckInterval);\n }\n\n // Perform cleanup\n await this.cleanup();\n\n process.exit(0);\n };\n\n process.on('SIGTERM', () => {\n void gracefulShutdown('SIGTERM');\n });\n process.on('SIGINT', () => {\n void gracefulShutdown('SIGINT');\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n logger.error('[Bootstrap] Unhandled rejection', {\n reason,\n promise,\n });\n });\n\n process.on('uncaughtException', (error) => {\n logger.error('[Bootstrap] Uncaught exception', { error });\n process.exit(1);\n });\n }\n\n /**\n * Cleanup on shutdown\n */\n private async cleanup(): Promise<void> {\n logger.info('[Bootstrap] Performing cleanup');\n\n // Gracefully close every registered long-lived connection (Redis Streams\n // event publisher/consumer, cache client) so their sockets are torn down\n // deterministically here instead of being left for the OS at process exit.\n // Bounded per-connection so a hung close never blocks the exit. Never throws.\n await disposeAll();\n\n // Clear context\n ContextManager.clearContext();\n\n logger.info('[Bootstrap] Cleanup completed');\n }\n\n /**\n * Get application info\n */\n public getInfo(): {\n serviceName: string;\n serviceVersion: string;\n environment: string;\n uptime: number;\n startedAt: string;\n } {\n return {\n serviceName: this.config.serviceName || 'burdenoff-service',\n serviceVersion: this.config.serviceVersion || '1.0.0',\n environment: this.config.environment || 'development',\n uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1000),\n startedAt: this.startTime.toISOString(),\n };\n }\n\n /**\n * Setup default context\n */\n public setupDefaultContext(context: SDKContext): void {\n logger.debug('[Bootstrap] Setting up default context', context);\n ContextManager.setContext(context);\n }\n\n /**\n * Create context middleware (for Elysia/HTTP frameworks)\n */\n public createContextMiddleware() {\n return async (\n req: { headers: Record<string, HeaderValue>; user?: unknown },\n _res: unknown,\n next: () => void\n ): Promise<void> => {\n const context = this.extractContextFromRequest(\n req as {\n headers: Record<string, HeaderValue>;\n user?: { user_id?: string; workspace_id?: string; org_id?: string; tenant_endpoint?: string };\n }\n );\n ContextManager.setContext(context);\n next();\n };\n }\n\n /**\n * Extract context from request\n */\n private extractContextFromRequest(req: {\n headers: Record<string, string | string[] | undefined>;\n user?: { user_id?: string; workspace_id?: string; org_id?: string; tenant_endpoint?: string };\n }): SDKContext {\n const context: SDKContext = {};\n\n // Extract from user object (if JWT already verified)\n if (req.user) {\n context.actorId = req.user.user_id;\n context.workspaceId = req.user.workspace_id;\n context.tenantId = req.user.tenant_endpoint;\n }\n\n // Extract from headers\n const getHeader = (key: string): string | undefined => {\n const value = req.headers[key.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n };\n\n const authHeader = getHeader('authorization');\n if (authHeader) {\n context.token = authHeader.replace('Bearer ', '');\n }\n\n const workspaceId = getHeader('x-workspace-id');\n if (workspaceId && !context.workspaceId) {\n context.workspaceId = workspaceId;\n }\n\n const productId = getHeader('x-product-id');\n if (productId) {\n context.productId = productId;\n }\n\n const projectId = getHeader('x-project-id');\n if (projectId) {\n context.projectId = projectId;\n }\n\n const appId = getHeader('x-app-id');\n if (appId) {\n context.appId = appId;\n }\n\n // Cloudflare Access service token — captured so cross-layer calls can\n // re-present it on alpha (see ContextManager.getCfAccessHeaders). Kept in\n // sync with the canonical extractor in `src/context/index.ts`. Setting it\n // via ContextManager.setContext (see createContextMiddleware) also mirrors\n // it to the module-level fallback for Bun + Yoga.\n const cfAccessClientId = getHeader('cf-access-client-id');\n if (cfAccessClientId) {\n context.cfAccessClientId = cfAccessClientId;\n }\n\n const cfAccessClientSecret = getHeader('cf-access-client-secret');\n if (cfAccessClientSecret) {\n context.cfAccessClientSecret = cfAccessClientSecret;\n }\n\n // Cloudflare Access user-SSO cookie, forwarded by the public gateway as\n // x-cf-authorization. Re-presented as the CF_Authorization cookie on\n // cross-layer calls (see ContextManager.getCfAccessHeaders). See BOFF-2929.\n const cfAuthorization = getHeader('x-cf-authorization');\n if (cfAuthorization) {\n context.cfAuthorization = cfAuthorization;\n }\n\n return context;\n }\n\n /**\n * Load GraphQL schema\n */\n public async loadSchema(schemaPath: string): Promise<boolean> {\n logger.info('[Bootstrap] Loading GraphQL schema', { schemaPath });\n\n try {\n // Schema loading logic would go here\n // This is typically handled by the GraphQL server setup\n logger.info('[Bootstrap] Schema loaded successfully');\n return true;\n } catch (error) {\n logger.error('[Bootstrap] Failed to load schema', { error });\n return false;\n }\n }\n\n /**\n * Register shutdown hook\n */\n public onShutdown(callback: () => Promise<void> | void): void {\n const originalHandler = process.listeners('SIGTERM')[0] as (() => void) | undefined;\n\n process.removeAllListeners('SIGTERM');\n process.on('SIGTERM', () => {\n void (async () => {\n await callback();\n if (typeof originalHandler === 'function') {\n originalHandler();\n }\n })();\n });\n }\n\n /**\n * Check if application is ready\n */\n public async isReady(): Promise<boolean> {\n const health = await this.performHealthCheck();\n return health.healthy;\n }\n\n /**\n * Get metrics\n */\n public getMetrics(): {\n memory: NodeJS.MemoryUsage;\n uptime: number;\n cpu: NodeJS.CpuUsage;\n } {\n return {\n memory: process.memoryUsage(),\n uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1000),\n cpu: process.cpuUsage(),\n };\n }\n}\n\n/**\n * Create bootstrap instance\n */\nexport function createBootstrap(config: BootstrapConfig): BootstrapModule {\n return new BootstrapModule(config);\n}\n"],"mappings":";;;;;;;;;;;;;AAgEA,IAAa,kBAAb,MAA6B;CAC3B,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,QAAyB;EACnC,KAAK,SAAS;EACd,KAAK,4BAAY,IAAI,KAAK;CAC5B;;;;CAKA,MAAa,YAAsC;EACjD,OAAO,KAAK,8CAA8C;GACxD,aAAa,KAAK,OAAO;GACzB,aAAa,KAAK,OAAO,eAAe;EAC1C,CAAC;EAED,IAAI;GAEF,MAAM,KAAK,sBAAsB;GAGjC,MAAM,oBAAoB,MAAM,KAAK,gBAAgB;GAGrD,MAAM,gBAAgB,MAAM,KAAK,YAAY;GAG7C,IAAI,KAAK,OAAO,aACd,MAAM,KAAK,kBAAkB;GAI/B,KAAK,oBAAoB;GAEzB,MAAM,SAA0B;IAC9B,SAAS;IACT,aAAa,KAAK,OAAO,eAAe;IACxC,gBAAgB,KAAK,OAAO,kBAAkB;IAC9C,aAAa,KAAK,OA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../../src/bootstrap/index.ts"],"sourcesContent":["/**\n * Bootstrap Module\n * Helpers for bootstrapping server, loading modules, and setting up schemas\n */\n\nimport { logger } from '../logger/index.js';\nimport { DatabaseModule, type DatabaseConfig } from '../database/index.js';\nimport { ContextManager } from '../context/index.js';\nimport { disposeAll } from '../lifecycle/index.js';\nimport type { SDKConfig, SDKContext } from '../types/index.js';\n\n/**\n * Type for HTTP header values\n */\ntype HeaderValue = string | string[] | undefined;\n\nexport interface BootstrapConfig extends SDKConfig {\n /** Database configuration */\n database?: DatabaseConfig;\n /** Enable health checks */\n healthCheck?: boolean;\n /** Health check interval in milliseconds */\n healthCheckInterval?: number;\n /** Modules to load */\n modules?: string[];\n /** Environment */\n environment?: 'development' | 'staging' | 'production';\n /** Service name */\n serviceName?: string;\n /** Service version */\n serviceVersion?: string;\n /** Port to run health check server */\n healthCheckPort?: number;\n}\n\nexport interface BootstrapResult {\n success: boolean;\n serviceName: string;\n serviceVersion: string;\n environment: string;\n startedAt: string;\n modules: string[];\n databaseConnected: boolean;\n healthCheckEnabled: boolean;\n}\n\nexport interface BootstrapHealthCheckResult {\n healthy: boolean;\n checks: {\n database?: boolean;\n graphql?: boolean;\n memory?: {\n used: number;\n total: number;\n percentage: number;\n };\n uptime?: number;\n };\n timestamp: string;\n}\n\n/**\n * Bootstrap Module\n */\nexport class BootstrapModule {\n private config: BootstrapConfig;\n private startTime: Date;\n private healthCheckInterval?: NodeJS.Timeout;\n\n constructor(config: BootstrapConfig) {\n this.config = config;\n this.startTime = new Date();\n }\n\n /**\n * Bootstrap the application\n */\n public async bootstrap(): Promise<BootstrapResult> {\n logger.info('[Bootstrap] Starting application bootstrap', {\n serviceName: this.config.serviceName,\n environment: this.config.environment || 'development',\n });\n\n try {\n // 1. Validate configuration\n await this.validateConfiguration();\n\n // 2. Connect to database\n const databaseConnected = await this.connectDatabase();\n\n // 3. Load modules\n const loadedModules = await this.loadModules();\n\n // 4. Setup health checks\n if (this.config.healthCheck) {\n await this.setupHealthChecks();\n }\n\n // 5. Setup signal handlers\n this.setupSignalHandlers();\n\n const result: BootstrapResult = {\n success: true,\n serviceName: this.config.serviceName || 'burdenoff-service',\n serviceVersion: this.config.serviceVersion || '1.0.0',\n environment: this.config.environment || 'development',\n startedAt: this.startTime.toISOString(),\n modules: loadedModules,\n databaseConnected,\n healthCheckEnabled: this.config.healthCheck || false,\n };\n\n logger.info('[Bootstrap] Application bootstrapped successfully', result);\n\n return result;\n } catch (error) {\n logger.error('[Bootstrap] Failed to bootstrap application', { error });\n throw error;\n }\n }\n\n /**\n * Validate configuration\n */\n private async validateConfiguration(): Promise<void> {\n logger.debug('[Bootstrap] Validating configuration');\n\n if (!this.config.workspacesApiUrl) {\n throw new Error('Workspaces API URL is required');\n }\n\n if (this.config.database?.url && !DatabaseModule.validateDatabaseUrl(this.config.database.url)) {\n throw new Error('Invalid database URL');\n }\n\n logger.debug('[Bootstrap] Configuration validated');\n }\n\n /**\n * Connect to database\n */\n private async connectDatabase(): Promise<boolean> {\n if (!this.config.database) {\n logger.debug('[Bootstrap] No database configuration provided, skipping');\n return false;\n }\n\n logger.info('[Bootstrap] Connecting to database');\n\n try {\n // Database connection is typically handled by Prisma or other ORM\n // This is a placeholder for validation and logging\n const sanitizedUrl = DatabaseModule.sanitizeDatabaseUrl(this.config.database.url);\n logger.info('[Bootstrap] Database connection configured', { url: sanitizedUrl });\n\n return true;\n } catch (error) {\n logger.error('[Bootstrap] Failed to connect to database', { error });\n return false;\n }\n }\n\n /**\n * Load modules\n */\n private async loadModules(): Promise<string[]> {\n const modules = this.config.modules || [];\n\n if (modules.length === 0) {\n logger.debug('[Bootstrap] No modules to load');\n return [];\n }\n\n logger.info('[Bootstrap] Loading modules', { modules });\n\n const loadedModules: string[] = [];\n\n for (const moduleName of modules) {\n try {\n logger.debug(`[Bootstrap] Loading module: ${moduleName}`);\n // Module loading logic would go here\n loadedModules.push(moduleName);\n } catch (error) {\n logger.error(`[Bootstrap] Failed to load module: ${moduleName}`, { error });\n }\n }\n\n logger.info('[Bootstrap] Modules loaded', { loaded: loadedModules });\n\n return loadedModules;\n }\n\n /**\n * Setup health checks\n */\n private async setupHealthChecks(): Promise<void> {\n logger.info('[Bootstrap] Setting up health checks');\n\n const interval = this.config.healthCheckInterval || 30000; // 30 seconds\n\n this.healthCheckInterval = setInterval(() => {\n void (async () => {\n const health = await this.performHealthCheck();\n\n if (!health.healthy) {\n logger.warn('[Bootstrap] Health check failed', health);\n } else {\n logger.debug('[Bootstrap] Health check passed', health);\n }\n })();\n }, interval);\n\n logger.info('[Bootstrap] Health checks configured', { interval });\n }\n\n /**\n * Perform health check\n */\n public async performHealthCheck(): Promise<BootstrapHealthCheckResult> {\n const checks: BootstrapHealthCheckResult['checks'] = {};\n\n // Memory check\n const memUsage = process.memoryUsage();\n checks.memory = {\n used: memUsage.heapUsed,\n total: memUsage.heapTotal,\n percentage: (memUsage.heapUsed / memUsage.heapTotal) * 100,\n };\n\n // Uptime\n checks.uptime = Math.floor((Date.now() - this.startTime.getTime()) / 1000);\n\n // Determine overall health\n const healthy =\n checks.memory.percentage < 90 && // Less than 90% memory usage\n checks.uptime > 0;\n\n return {\n healthy,\n checks,\n timestamp: new Date().toISOString(),\n };\n }\n\n /**\n * Setup signal handlers for graceful shutdown\n */\n private setupSignalHandlers(): void {\n logger.debug('[Bootstrap] Setting up signal handlers');\n\n const gracefulShutdown = async (signal: string): Promise<void> => {\n logger.info(`[Bootstrap] Received ${signal}, shutting down gracefully`);\n\n // Clear health check interval\n if (this.healthCheckInterval) {\n clearInterval(this.healthCheckInterval);\n }\n\n // Perform cleanup\n await this.cleanup();\n\n process.exit(0);\n };\n\n process.on('SIGTERM', () => {\n void gracefulShutdown('SIGTERM');\n });\n process.on('SIGINT', () => {\n void gracefulShutdown('SIGINT');\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n logger.error('[Bootstrap] Unhandled rejection', {\n reason,\n promise,\n });\n });\n\n process.on('uncaughtException', (error) => {\n logger.error('[Bootstrap] Uncaught exception', { error });\n process.exit(1);\n });\n }\n\n /**\n * Cleanup on shutdown\n */\n private async cleanup(): Promise<void> {\n logger.info('[Bootstrap] Performing cleanup');\n\n // Gracefully close every registered long-lived connection (Redis Streams\n // event publisher/consumer, cache client) so their sockets are torn down\n // deterministically here instead of being left for the OS at process exit.\n // Bounded per-connection so a hung close never blocks the exit. Never throws.\n await disposeAll();\n\n // Clear context\n ContextManager.clearContext();\n\n logger.info('[Bootstrap] Cleanup completed');\n }\n\n /**\n * Get application info\n */\n public getInfo(): {\n serviceName: string;\n serviceVersion: string;\n environment: string;\n uptime: number;\n startedAt: string;\n } {\n return {\n serviceName: this.config.serviceName || 'burdenoff-service',\n serviceVersion: this.config.serviceVersion || '1.0.0',\n environment: this.config.environment || 'development',\n uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1000),\n startedAt: this.startTime.toISOString(),\n };\n }\n\n /**\n * Setup default context\n */\n public setupDefaultContext(context: SDKContext): void {\n logger.debug('[Bootstrap] Setting up default context', context);\n ContextManager.setContext(context);\n }\n\n /**\n * Create context middleware (for Elysia/HTTP frameworks)\n */\n public createContextMiddleware() {\n return async (\n req: { headers: Record<string, HeaderValue>; user?: unknown },\n _res: unknown,\n next: () => void\n ): Promise<void> => {\n const context = this.extractContextFromRequest(\n req as {\n headers: Record<string, HeaderValue>;\n user?: { user_id?: string; workspace_id?: string; org_id?: string; tenant_endpoint?: string };\n }\n );\n ContextManager.setContext(context);\n next();\n };\n }\n\n /**\n * Extract context from request\n */\n private extractContextFromRequest(req: {\n headers: Record<string, string | string[] | undefined>;\n user?: { user_id?: string; workspace_id?: string; org_id?: string; tenant_endpoint?: string };\n }): SDKContext {\n const context: SDKContext = {};\n\n // Extract from user object (if JWT already verified)\n if (req.user) {\n context.actorId = req.user.user_id;\n context.workspaceId = req.user.workspace_id;\n context.tenantId = req.user.tenant_endpoint;\n }\n\n // Extract from headers\n const getHeader = (key: string): string | undefined => {\n const value = req.headers[key.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n };\n\n const authHeader = getHeader('authorization');\n if (authHeader) {\n context.token = authHeader.replace('Bearer ', '');\n }\n\n const workspaceId = getHeader('x-workspace-id');\n if (workspaceId && !context.workspaceId) {\n context.workspaceId = workspaceId;\n }\n\n const productId = getHeader('x-product-id');\n if (productId) {\n context.productId = productId;\n }\n\n const projectId = getHeader('x-project-id');\n if (projectId) {\n context.projectId = projectId;\n }\n\n const appId = getHeader('x-app-id');\n if (appId) {\n context.appId = appId;\n }\n\n // Cloudflare Access service token — captured so cross-layer calls can\n // re-present it on alpha (see ContextManager.getCfAccessHeaders). Kept in\n // sync with the canonical extractor in `src/context/index.ts`. It lives only\n // in the context bound for this request (see createContextMiddleware).\n const cfAccessClientId = getHeader('cf-access-client-id');\n if (cfAccessClientId) {\n context.cfAccessClientId = cfAccessClientId;\n }\n\n const cfAccessClientSecret = getHeader('cf-access-client-secret');\n if (cfAccessClientSecret) {\n context.cfAccessClientSecret = cfAccessClientSecret;\n }\n\n // Cloudflare Access user-SSO cookie, forwarded by the public gateway as\n // x-cf-authorization. Re-presented as the CF_Authorization cookie on\n // cross-layer calls (see ContextManager.getCfAccessHeaders). See BOFF-2929.\n const cfAuthorization = getHeader('x-cf-authorization');\n if (cfAuthorization) {\n context.cfAuthorization = cfAuthorization;\n }\n\n return context;\n }\n\n /**\n * Load GraphQL schema\n */\n public async loadSchema(schemaPath: string): Promise<boolean> {\n logger.info('[Bootstrap] Loading GraphQL schema', { schemaPath });\n\n try {\n // Schema loading logic would go here\n // This is typically handled by the GraphQL server setup\n logger.info('[Bootstrap] Schema loaded successfully');\n return true;\n } catch (error) {\n logger.error('[Bootstrap] Failed to load schema', { error });\n return false;\n }\n }\n\n /**\n * Register shutdown hook\n */\n public onShutdown(callback: () => Promise<void> | void): void {\n const originalHandler = process.listeners('SIGTERM')[0] as (() => void) | undefined;\n\n process.removeAllListeners('SIGTERM');\n process.on('SIGTERM', () => {\n void (async () => {\n await callback();\n if (typeof originalHandler === 'function') {\n originalHandler();\n }\n })();\n });\n }\n\n /**\n * Check if application is ready\n */\n public async isReady(): Promise<boolean> {\n const health = await this.performHealthCheck();\n return health.healthy;\n }\n\n /**\n * Get metrics\n */\n public getMetrics(): {\n memory: NodeJS.MemoryUsage;\n uptime: number;\n cpu: NodeJS.CpuUsage;\n } {\n return {\n memory: process.memoryUsage(),\n uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1000),\n cpu: process.cpuUsage(),\n };\n }\n}\n\n/**\n * Create bootstrap instance\n */\nexport function createBootstrap(config: BootstrapConfig): BootstrapModule {\n return new BootstrapModule(config);\n}\n"],"mappings":";;;;;;;;;;;;;AAgEA,IAAa,kBAAb,MAA6B;CAC3B,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,QAAyB;EACnC,KAAK,SAAS;EACd,KAAK,4BAAY,IAAI,KAAK;CAC5B;;;;CAKA,MAAa,YAAsC;EACjD,OAAO,KAAK,8CAA8C;GACxD,aAAa,KAAK,OAAO;GACzB,aAAa,KAAK,OAAO,eAAe;EAC1C,CAAC;EAED,IAAI;GAEF,MAAM,KAAK,sBAAsB;GAGjC,MAAM,oBAAoB,MAAM,KAAK,gBAAgB;GAGrD,MAAM,gBAAgB,MAAM,KAAK,YAAY;GAG7C,IAAI,KAAK,OAAO,aACd,MAAM,KAAK,kBAAkB;GAI/B,KAAK,oBAAoB;GAEzB,MAAM,SAA0B;IAC9B,SAAS;IACT,aAAa,KAAK,OAAO,eAAe;IACxC,gBAAgB,KAAK,OAAO,kBAAkB;IAC9C,aAAa,KAAK,OAAO,eAAe;IACxC,WAAW,KAAK,UAAU,YAAY;IACtC,SAAS;IACT;IACA,oBAAoB,KAAK,OAAO,eAAe;GACjD;GAEA,OAAO,KAAK,qDAAqD,MAAM;GAEvE,OAAO;EACT,SAAS,OAAO;GACd,OAAO,MAAM,+CAA+C,EAAE,MAAM,CAAC;GACrE,MAAM;EACR;CACF;;;;CAKA,MAAc,wBAAuC;EACnD,OAAO,MA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,MAAM,uBAAuB,UAAU,yBAAyB;EAChE,IAAI,sBACF,QAAQ,uBAAuB;EAMjC,MAAM,kBAAkB,UAAU,oBAAoB;EACtD,IAAI,iBACF,QAAQ,kBAAkB;EAG5B,OAAO;CACT;;;;CAKA,MAAa,WAAW,YAAsC;EAC5D,OAAO,KAAK,sCAAsC,EAAE,WAAW,CAAC;EAEhE,IAAI;GAGF,OAAO,KAAK,wCAAwC;GACpD,OAAO;EACT,SAAS,OAAO;GACd,OAAO,MAAM,qCAAqC,EAAE,MAAM,CAAC;GAC3D,OAAO;EACT;CACF;;;;CAKA,AAAO,WAAW,UAA4C;EAC5D,MAAM,kBAAkB,QAAQ,UAAU,SAAS,CAAC,CAAC;EAErD,QAAQ,mBAAmB,SAAS;EACpC,QAAQ,GAAG,iBAAiB;GAC1B,CAAM,YAAY;IAChB,MAAM,SAAS;IACf,IAAI,OAAO,oBAAoB,YAC7B,gBAAgB;GAEpB,EAAC,CAAE;EACL,CAAC;CACH;;;;CAKA,MAAa,UAA4B;EAEvC,QAAO,MADc,KAAK,mBAAmB,EAChC,CAAC;CAChB;;;;CAKA,AAAO,aAIL;EACA,OAAO;GACL,QAAQ,QAAQ,YAAY;GAC5B,QAAQ,KAAK,OAAO,KAAK,IAAI,IAAI,KAAK,UAAU,QAAQ,KAAK,GAAI;GACjE,KAAK,QAAQ,SAAS;EACxB;CACF;AACF;;;;AAKA,SAAgB,gBAAgB,QAA0C;CACxE,OAAO,IAAI,gBAAgB,MAAM;AACnC"}
|
package/dist/context/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { m as SDKContext } from "../index-CQ3vxT5P.js";
|
|
2
2
|
export declare class ContextManager {
|
|
3
3
|
static getContext(): SDKContext | undefined;
|
|
4
4
|
static setContext(context: SDKContext): void;
|
|
5
|
-
static
|
|
5
|
+
static configureCfAccessServiceToken(clientId?: string, clientSecret?: string): void;
|
|
6
|
+
static setCfAccessContext(clientId?: string, clientSecret?: string, _cfAuthorization?: string): void;
|
|
6
7
|
static withContext<T>(context: SDKContext, fn: () => Promise<T>): Promise<T>;
|
|
7
8
|
static withContextSync<T>(context: SDKContext, fn: () => T): T;
|
|
8
9
|
static clearContext(): void;
|
package/dist/context/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { c as getScopedWorkspaceContext } from "../workspace-extension-ByopOwtK.js";
|
|
1
2
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
3
|
|
|
3
4
|
// src/context/index.ts
|
|
@@ -8,36 +9,52 @@ import { AsyncLocalStorage } from "node:async_hooks";
|
|
|
8
9
|
*/
|
|
9
10
|
const asyncLocalStorage = new AsyncLocalStorage();
|
|
10
11
|
/**
|
|
11
|
-
*
|
|
12
|
+
* A Cloudflare Access service token the service configured for itself, from its own
|
|
13
|
+
* configuration (for example `CF_ACCESS_CLIENT_ID` / `CF_ACCESS_CLIENT_SECRET` in its
|
|
14
|
+
* environment), via {@link ContextManager.configureCfAccessServiceToken}.
|
|
12
15
|
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* limitation documented for the Prisma workspace context store
|
|
17
|
-
* (see `src/prisma/workspace-extension.ts`). On top of that, the `createServer`
|
|
18
|
-
* request path (`src/server/context.ts` `buildContext`) populates the *Prisma*
|
|
19
|
-
* workspace store, not this `ContextManager` ALS at all. So a resolver-initiated
|
|
20
|
-
* cross-layer call would otherwise read an empty context and attach no CF creds,
|
|
21
|
-
* making the propagation a silent no-op on alpha.
|
|
22
|
-
*
|
|
23
|
-
* Unlike workspaceId/actorId (which differ per request and would race in a
|
|
24
|
-
* module-level singleton), the CF Access service token is effectively
|
|
25
|
-
* CONSTANT per environment — it's a single service-token pair fronting the
|
|
26
|
-
* gateway. So caching it module-side is race-safe: concurrent requests all
|
|
27
|
-
* carry the same value. It is only ever set when a request actually presents
|
|
28
|
-
* the headers (gated upstream on `cf-ray`), and stays unset in dev/prod where
|
|
29
|
-
* no CF Access sits in front of the gateways.
|
|
16
|
+
* This is the only process-wide Cloudflare Access state. It is never written from request
|
|
17
|
+
* data: credentials an inbound request presented live only in that request's bound async
|
|
18
|
+
* scope (see {@link ContextManager.getCfAccessHeaders}).
|
|
30
19
|
*/
|
|
31
|
-
let
|
|
20
|
+
let configuredServiceToken;
|
|
21
|
+
function nonEmpty(value) {
|
|
22
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
23
|
+
}
|
|
32
24
|
/**
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
* the CF edge any valid member cookie suffices (app-layer identity travels in
|
|
37
|
-
* `x-actor-*`). Refreshed by every inbound CF request, so an active fleet keeps
|
|
38
|
-
* a live value. See BOFF-2929.
|
|
25
|
+
* The Cloudflare Access credentials bound to the current async scope: the ContextManager
|
|
26
|
+
* store first, then the request scope the SDK server binds for GraphQL execution and REST
|
|
27
|
+
* handlers. Reads only bound stores, never the deprecated warn-mode workspace fallback.
|
|
39
28
|
*/
|
|
40
|
-
|
|
29
|
+
function scopedCfAccess() {
|
|
30
|
+
const context = asyncLocalStorage.getStore();
|
|
31
|
+
const fromContext = {
|
|
32
|
+
clientId: nonEmpty(context?.cfAccessClientId),
|
|
33
|
+
clientSecret: nonEmpty(context?.cfAccessClientSecret),
|
|
34
|
+
authorization: nonEmpty(context?.cfAuthorization)
|
|
35
|
+
};
|
|
36
|
+
const fromRequestScope = getScopedWorkspaceContext()?.cfAccess;
|
|
37
|
+
const contextHasPair = Boolean(fromContext.clientId && fromContext.clientSecret);
|
|
38
|
+
const scopeHasPair = Boolean(fromRequestScope?.clientId && fromRequestScope.clientSecret);
|
|
39
|
+
const pair = contextHasPair ? fromContext : scopeHasPair ? fromRequestScope : void 0;
|
|
40
|
+
const authorization = fromContext.authorization ?? nonEmpty(fromRequestScope?.authorization);
|
|
41
|
+
if (!pair && !authorization) return void 0;
|
|
42
|
+
return {
|
|
43
|
+
...pair ? {
|
|
44
|
+
clientId: pair.clientId,
|
|
45
|
+
clientSecret: pair.clientSecret
|
|
46
|
+
} : {},
|
|
47
|
+
...authorization ? { authorization } : {}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** The service-token pair for the current scope, else the token the service configured. */
|
|
51
|
+
function serviceTokenPair(scoped = scopedCfAccess()) {
|
|
52
|
+
if (scoped?.clientId && scoped.clientSecret) return {
|
|
53
|
+
clientId: scoped.clientId,
|
|
54
|
+
clientSecret: scoped.clientSecret
|
|
55
|
+
};
|
|
56
|
+
return configuredServiceToken;
|
|
57
|
+
}
|
|
41
58
|
/**
|
|
42
59
|
* Context Manager for handling request-scoped context
|
|
43
60
|
*/
|
|
@@ -58,28 +75,41 @@ var ContextManager = class {
|
|
|
58
75
|
...currentContext,
|
|
59
76
|
...context
|
|
60
77
|
});
|
|
61
|
-
if (context.cfAccessClientId && context.cfAccessClientSecret || context.cfAuthorization) this.setCfAccessContext(context.cfAccessClientId, context.cfAccessClientSecret, context.cfAuthorization);
|
|
62
78
|
}
|
|
63
79
|
/**
|
|
64
|
-
*
|
|
80
|
+
* Configure a Cloudflare Access service token the service holds for itself, read from its own
|
|
81
|
+
* configuration (never from a request). Cross-layer calls attach it when the current request
|
|
82
|
+
* scope carries no service-token pair of its own, which lets background work (stream
|
|
83
|
+
* consumers, schedulers, CLIs) pass a Cloudflare-Access-gated peer gateway.
|
|
65
84
|
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
* both do). Stored in a module-level fallback because `enterWith()` is not a
|
|
69
|
-
* reliable carrier under Bun + Yoga — see the `cfAccessFallback` note above.
|
|
85
|
+
* Pass both values to set the token, or call it with no arguments to remove it. A lone half
|
|
86
|
+
* is ignored, since it can never pass Access.
|
|
70
87
|
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
* `clearContext()` to reset (shutdown / tests).
|
|
88
|
+
* @example
|
|
89
|
+
* ```typescript
|
|
90
|
+
* ContextManager.configureCfAccessServiceToken(process.env.CF_ACCESS_CLIENT_ID, process.env.CF_ACCESS_CLIENT_SECRET);
|
|
91
|
+
* ```
|
|
76
92
|
*/
|
|
77
|
-
static
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
93
|
+
static configureCfAccessServiceToken(clientId, clientSecret) {
|
|
94
|
+
const id = nonEmpty(clientId);
|
|
95
|
+
const secret = nonEmpty(clientSecret);
|
|
96
|
+
if (id && secret) configuredServiceToken = {
|
|
97
|
+
clientId: id,
|
|
98
|
+
clientSecret: secret
|
|
81
99
|
};
|
|
82
|
-
if (
|
|
100
|
+
else if (id === void 0 && secret === void 0) configuredServiceToken = void 0;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* @deprecated Use {@link ContextManager.configureCfAccessServiceToken} with the service's own
|
|
104
|
+
* token. Credentials a request presents no longer need recording: the SDK server binds them
|
|
105
|
+
* to that request's scope.
|
|
106
|
+
*
|
|
107
|
+
* Kept for services that seed their own token from configuration. It sets the service token
|
|
108
|
+
* when both values are present and otherwise does nothing. The `CF_Authorization` cookie is a
|
|
109
|
+
* per-user credential, so it is never stored process-wide and the third argument is ignored.
|
|
110
|
+
*/
|
|
111
|
+
static setCfAccessContext(clientId, clientSecret, _cfAuthorization) {
|
|
112
|
+
if (nonEmpty(clientId) && nonEmpty(clientSecret)) this.configureCfAccessServiceToken(clientId, clientSecret);
|
|
83
113
|
}
|
|
84
114
|
/**
|
|
85
115
|
* Run function with specific context
|
|
@@ -95,12 +125,11 @@ var ContextManager = class {
|
|
|
95
125
|
return asyncLocalStorage.run(context, fn);
|
|
96
126
|
}
|
|
97
127
|
/**
|
|
98
|
-
* Clear current context
|
|
128
|
+
* Clear current context, including any configured Cloudflare Access service token.
|
|
99
129
|
*/
|
|
100
130
|
static clearContext() {
|
|
101
131
|
asyncLocalStorage.disable();
|
|
102
|
-
|
|
103
|
-
cfAuthorizationFallback = void 0;
|
|
132
|
+
configuredServiceToken = void 0;
|
|
104
133
|
}
|
|
105
134
|
/**
|
|
106
135
|
* Get actor ID from context
|
|
@@ -160,51 +189,50 @@ var ContextManager = class {
|
|
|
160
189
|
return this.getContext()?.productId;
|
|
161
190
|
}
|
|
162
191
|
/**
|
|
163
|
-
*
|
|
164
|
-
*
|
|
192
|
+
* The Cloudflare Access service-token client id for the current request scope, else the
|
|
193
|
+
* service's configured token. Undefined outside a bound scope unless a token is configured.
|
|
165
194
|
*/
|
|
166
195
|
static getCfAccessClientId() {
|
|
167
|
-
return
|
|
196
|
+
return serviceTokenPair()?.clientId;
|
|
168
197
|
}
|
|
169
198
|
/**
|
|
170
|
-
*
|
|
171
|
-
*
|
|
199
|
+
* The Cloudflare Access service-token client secret, resolved together with
|
|
200
|
+
* {@link ContextManager.getCfAccessClientId}.
|
|
172
201
|
*/
|
|
173
202
|
static getCfAccessClientSecret() {
|
|
174
|
-
return
|
|
203
|
+
return serviceTokenPair()?.clientSecret;
|
|
175
204
|
}
|
|
176
205
|
/**
|
|
177
|
-
*
|
|
178
|
-
*
|
|
206
|
+
* The `CF_Authorization` cookie value the current request presented. Read only from the bound
|
|
207
|
+
* request scope: it is a per-user credential and is never shared across requests.
|
|
179
208
|
*/
|
|
180
209
|
static getCfAuthorization() {
|
|
181
|
-
return
|
|
210
|
+
return scopedCfAccess()?.authorization;
|
|
182
211
|
}
|
|
183
212
|
/**
|
|
184
|
-
* Build the Cloudflare Access credentials to re-present on a
|
|
185
|
-
* cross-layer outbound call.
|
|
213
|
+
* Build the Cloudflare Access credentials to re-present on a cross-layer outbound call.
|
|
186
214
|
*
|
|
187
|
-
*
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
*
|
|
191
|
-
*
|
|
215
|
+
* Sources, in order:
|
|
216
|
+
* 1. The credentials the current request presented, read only from its bound async scope
|
|
217
|
+
* (the ContextManager store, or the request scope the SDK server binds for GraphQL
|
|
218
|
+
* execution and REST handlers).
|
|
219
|
+
* 2. For the service-token pair only, a token the service configured for itself with
|
|
220
|
+
* {@link ContextManager.configureCfAccessServiceToken}.
|
|
192
221
|
*
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
* CF-Access-gated and has no CF service token).
|
|
222
|
+
* Fails closed: outside a bound request scope, and with no configured token, it returns `{}`.
|
|
223
|
+
* Credentials one request presented are never attached to another request or to background
|
|
224
|
+
* work. It is also `{}` wherever no Cloudflare Access fronts the gateways (local dev and
|
|
225
|
+
* production).
|
|
198
226
|
*/
|
|
199
227
|
static getCfAccessHeaders() {
|
|
200
228
|
const headers = {};
|
|
201
|
-
const
|
|
202
|
-
const
|
|
203
|
-
if (
|
|
204
|
-
headers["cf-access-client-id"] = clientId;
|
|
205
|
-
headers["cf-access-client-secret"] = clientSecret;
|
|
229
|
+
const scoped = scopedCfAccess();
|
|
230
|
+
const pair = serviceTokenPair(scoped);
|
|
231
|
+
if (pair) {
|
|
232
|
+
headers["cf-access-client-id"] = pair.clientId;
|
|
233
|
+
headers["cf-access-client-secret"] = pair.clientSecret;
|
|
206
234
|
}
|
|
207
|
-
const cfAuthorization =
|
|
235
|
+
const cfAuthorization = scoped?.authorization;
|
|
208
236
|
if (cfAuthorization) headers["cookie"] = `CF_Authorization=${cfAuthorization}`;
|
|
209
237
|
return headers;
|
|
210
238
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/context/index.ts"],"sourcesContent":["/**\n * Context Module\n * Manages request-scoped context using AsyncLocalStorage\n * Thread-safe context propagation for async operations\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { SDKContext } from '../types/index.js';\n\nconst asyncLocalStorage = new AsyncLocalStorage<SDKContext>();\n\n/**\n * Module-level fallback for the Cloudflare Access service token.\n *\n * WHY THIS EXISTS — read before \"simplifying\" it away:\n * `asyncLocalStorage.enterWith()` (used by `setContext`) does NOT reliably\n * propagate across every async boundary under Bun + GraphQL Yoga — the same\n * limitation documented for the Prisma workspace context store\n * (see `src/prisma/workspace-extension.ts`). On top of that, the `createServer`\n * request path (`src/server/context.ts` `buildContext`) populates the *Prisma*\n * workspace store, not this `ContextManager` ALS at all. So a resolver-initiated\n * cross-layer call would otherwise read an empty context and attach no CF creds,\n * making the propagation a silent no-op on alpha.\n *\n * Unlike workspaceId/actorId (which differ per request and would race in a\n * module-level singleton), the CF Access service token is effectively\n * CONSTANT per environment — it's a single service-token pair fronting the\n * gateway. So caching it module-side is race-safe: concurrent requests all\n * carry the same value. It is only ever set when a request actually presents\n * the headers (gated upstream on `cf-ray`), and stays unset in dev/prod where\n * no CF Access sits in front of the gateways.\n */\nlet cfAccessFallback: { clientId: string; clientSecret: string } | undefined;\n\n/**\n * Module-level fallback for the CF Access USER-SSO cookie (`CF_Authorization`),\n * mirroring `cfAccessFallback` for the same Bun+Yoga ALS-unreliability reason.\n * Unlike the service-token pair this is per-USER and ~1h TTL — but for passing\n * the CF edge any valid member cookie suffices (app-layer identity travels in\n * `x-actor-*`). Refreshed by every inbound CF request, so an active fleet keeps\n * a live value. See BOFF-2929.\n */\nlet cfAuthorizationFallback: string | undefined;\n\n/**\n * Context Manager for handling request-scoped context\n */\nexport class ContextManager {\n /**\n * Get current context from async local storage\n */\n public static getContext(): SDKContext | undefined {\n return asyncLocalStorage.getStore();\n }\n\n /**\n * Set context for current async scope\n * Merges with existing context if present\n */\n public static setContext(context: SDKContext): void {\n const currentContext = this.getContext() || {};\n asyncLocalStorage.enterWith({ ...currentContext, ...context });\n // Mirror CF creds to the module-level fallback so cross-layer calls can\n // recover them even when enterWith() doesn't reach the resolver chain.\n if ((context.cfAccessClientId && context.cfAccessClientSecret) || context.cfAuthorization) {\n this.setCfAccessContext(context.cfAccessClientId, context.cfAccessClientSecret, context.cfAuthorization);\n }\n }\n\n /**\n * Record the Cloudflare Access service token for the current process.\n *\n * Call this from every request-context builder that may receive CF headers\n * (the SDK `createServer` `buildContext` and the bootstrap HTTP middleware\n * both do). Stored in a module-level fallback because `enterWith()` is not a\n * reliable carrier under Bun + Yoga — see the `cfAccessFallback` note above.\n *\n * Deliberately a NO-OP when either cred is absent: `buildContext` runs on\n * every request, so clearing here on a tokenless request could wipe the value\n * a concurrent CF request just stored. The token is constant per environment,\n * so \"remember, never clear on absence\" is both safe and correct. Use\n * `clearContext()` to reset (shutdown / tests).\n */\n public static setCfAccessContext(clientId?: string, clientSecret?: string, cfAuthorization?: string): void {\n if (clientId && clientSecret) {\n cfAccessFallback = { clientId, clientSecret };\n }\n // CF Access user-SSO cookie — remember, never clear on absence (same policy\n // as the service token). Present on real alpha user requests; kept live by\n // ongoing traffic. See BOFF-2929.\n if (cfAuthorization) {\n cfAuthorizationFallback = cfAuthorization;\n }\n }\n\n /**\n * Run function with specific context\n * Context is isolated to this execution and its children\n */\n public static async withContext<T>(context: SDKContext, fn: () => Promise<T>): Promise<T> {\n return asyncLocalStorage.run(context, fn);\n }\n\n /**\n * Run synchronous function with specific context\n */\n public static withContextSync<T>(context: SDKContext, fn: () => T): T {\n return asyncLocalStorage.run(context, fn);\n }\n\n /**\n * Clear current context (including the module-level CF Access fallback).\n */\n public static clearContext(): void {\n asyncLocalStorage.disable();\n cfAccessFallback = undefined;\n cfAuthorizationFallback = undefined;\n }\n\n /**\n * Get actor ID from context\n */\n public static getActorId(): string | undefined {\n return this.getContext()?.actorId;\n }\n\n /**\n * Get legacy user ID from context.\n */\n public static getUser(): string | undefined {\n const context = this.getContext();\n const userId = context?.['userId'];\n return typeof userId === 'string' ? userId : context?.actorId;\n }\n\n /**\n * Get workspace ID from context\n */\n public static getWorkspace(): string | undefined {\n return this.getContext()?.workspaceId;\n }\n\n /**\n * Get tenant ID from context\n */\n public static getTenant(): string | undefined {\n return this.getContext()?.tenantId;\n }\n\n /**\n * Get legacy organization ID from context.\n */\n public static getOrganization(): string | undefined {\n const organizationId = this.getContext()?.['organizationId'];\n return typeof organizationId === 'string' ? organizationId : undefined;\n }\n\n /**\n * Get project ID from context\n */\n public static getProject(): string | undefined {\n return this.getContext()?.projectId;\n }\n\n /**\n * Get app ID from context\n */\n public static getApp(): string | undefined {\n return this.getContext()?.appId;\n }\n\n /**\n * Get JWT token from context\n */\n public static getToken(): string | undefined {\n return this.getContext()?.token;\n }\n\n /**\n * Get product ID from context\n */\n public static getProduct(): string | undefined {\n return this.getContext()?.productId;\n }\n\n /**\n * Get the Cloudflare Access service-token client id (ALS first, then the\n * module-level fallback — see `cfAccessFallback`).\n */\n public static getCfAccessClientId(): string | undefined {\n return this.getContext()?.cfAccessClientId ?? cfAccessFallback?.clientId;\n }\n\n /**\n * Get the Cloudflare Access service-token client secret (ALS first, then the\n * module-level fallback — see `cfAccessFallback`).\n */\n public static getCfAccessClientSecret(): string | undefined {\n return this.getContext()?.cfAccessClientSecret ?? cfAccessFallback?.clientSecret;\n }\n\n /**\n * Get the Cloudflare Access user-SSO cookie value (`CF_Authorization`) — ALS\n * first, then the module-level fallback (see `cfAuthorizationFallback`).\n */\n public static getCfAuthorization(): string | undefined {\n return this.getContext()?.cfAuthorization ?? cfAuthorizationFallback;\n }\n\n /**\n * Build the Cloudflare Access credentials to re-present on a\n * cross-layer outbound call.\n *\n * Cross-layer calls (wspace ↔ global) traverse the peer layer's PUBLIC\n * gateway, which on alpha sits behind Cloudflare Access. Without the CF\n * service token the request is rejected at the CF edge before reaching the\n * gateway. We reuse the *inbound* request's CF creds (propagated by the\n * public gateway into request-scoped context) so the cross-layer leg passes.\n *\n * Inbound-only: sourced from the request context (AsyncLocalStorage first,\n * module-level fallback second — see `cfAccessFallback`). Returns `{}` unless\n * BOTH creds are present — so it is a no-op in environments without CF in\n * front of the gateways (local dev, and production, which is not\n * CF-Access-gated and has no CF service token).\n */\n public static getCfAccessHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n\n // Service-token pair (machine callers). Present only when a service token\n // fronted the inbound call — not on browser user requests.\n const clientId = this.getCfAccessClientId();\n const clientSecret = this.getCfAccessClientSecret();\n if (clientId && clientSecret) {\n headers['cf-access-client-id'] = clientId;\n headers['cf-access-client-secret'] = clientSecret;\n }\n\n // User-SSO cookie. On alpha a real user request carries the CF_Authorization\n // cookie rather than the service-token pair; re-present it as the cookie so\n // the peer layer's CF Access (same app / shared AUD) admits the cross-layer\n // call. See BOFF-2929.\n const cfAuthorization = this.getCfAuthorization();\n if (cfAuthorization) {\n headers['cookie'] = `CF_Authorization=${cfAuthorization}`;\n }\n\n return headers;\n }\n\n /**\n * Update specific context fields\n */\n public static updateContext(updates: Partial<SDKContext>): void {\n const current = this.getContext();\n if (current) {\n this.setContext({ ...current, ...updates });\n } else {\n this.setContext(updates);\n }\n }\n\n /**\n * Check if context exists\n */\n public static hasContext(): boolean {\n return this.getContext() !== undefined;\n }\n\n /**\n * Get custom field from context\n */\n public static getCustomField(key: string): unknown {\n return this.getContext()?.[key];\n }\n\n /**\n * Set custom field in context\n */\n public static setCustomField(key: string, value: unknown): void {\n const current = this.getContext() || {};\n this.setContext({ ...current, [key]: value });\n }\n}\n\n/**\n * Default export for convenience\n */\nexport const contextManager = ContextManager;\n\n/**\n * Helper function to extract context from HTTP request\n */\nexport function extractContextFromRequest(req: {\n headers: Record<string, string | string[] | undefined>;\n user?: { user_id?: string; workspace_id?: string; tenant_endpoint?: string };\n}): SDKContext {\n const context: SDKContext = {};\n\n // Extract from user object (if JWT already verified)\n if (req.user) {\n context.actorId = req.user.user_id;\n context.workspaceId = req.user.workspace_id;\n context.tenantId = req.user.tenant_endpoint;\n }\n\n // Extract from headers\n const getHeader = (key: string): string | undefined => {\n const value = req.headers[key.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n };\n\n const authHeader = getHeader('authorization');\n if (authHeader) {\n context.token = authHeader.replace('Bearer ', '');\n }\n\n const workspaceId = getHeader('x-workspace-id');\n if (workspaceId && !context.workspaceId) {\n context.workspaceId = workspaceId;\n }\n\n const productId = getHeader('x-product-id');\n if (productId) {\n context.productId = productId;\n }\n\n const projectId = getHeader('x-project-id');\n if (projectId) {\n context.projectId = projectId;\n }\n\n const appId = getHeader('x-app-id');\n if (appId) {\n context.appId = appId;\n }\n\n // Cloudflare Access service token. Forwarded to subgraphs by the public\n // gateways only when the request actually transited CF (cf-ray present), so\n // we can capture whatever arrives here. Re-presented on cross-layer outbound\n // calls — see ContextManager.getCfAccessHeaders.\n const cfAccessClientId = getHeader('cf-access-client-id');\n if (cfAccessClientId) {\n context.cfAccessClientId = cfAccessClientId;\n }\n\n const cfAccessClientSecret = getHeader('cf-access-client-secret');\n if (cfAccessClientSecret) {\n context.cfAccessClientSecret = cfAccessClientSecret;\n }\n\n // CF Access user-SSO cookie, forwarded by the public gateway as\n // x-cf-authorization. Re-presented as the CF_Authorization cookie on\n // cross-layer calls (see getCfAccessHeaders). See BOFF-2929.\n const cfAuthorization = getHeader('x-cf-authorization');\n if (cfAuthorization) {\n context.cfAuthorization = cfAuthorization;\n }\n\n return context;\n}\n"],"mappings":";;;;;;;;AASA,MAAM,oBAAoB,IAAI,kBAA8B;;;;;;;;;;;;;;;;;;;;;;AAuB5D,IAAI;;;;;;;;;AAUJ,IAAI;;;;AAKJ,IAAa,iBAAb,MAA4B;;;;CAI1B,OAAc,aAAqC;EACjD,OAAO,kBAAkB,SAAS;CACpC;;;;;CAMA,OAAc,WAAW,SAA2B;EAClD,MAAM,iBAAiB,KAAK,WAAW,KAAK,CAAC;EAC7C,kBAAkB,UAAU;GAAE,GAAG;GAAgB,GAAG;EAAQ,CAAC;EAG7D,IAAK,QAAQ,oBAAoB,QAAQ,wBAAyB,QAAQ,iBACxE,KAAK,mBAAmB,QAAQ,kBAAkB,QAAQ,sBAAsB,QAAQ,eAAe;CAE3G;;;;;;;;;;;;;;;CAgBA,OAAc,mBAAmB,UAAmB,cAAuB,iBAAgC;EACzG,IAAI,YAAY,cACd,mBAAmB;GAAE;GAAU;EAAa;EAK9C,IAAI,iBACF,0BAA0B;CAE9B;;;;;CAMA,aAAoB,YAAe,SAAqB,IAAkC;EACxF,OAAO,kBAAkB,IAAI,SAAS,EAA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AY,UAAU,cAAc;CAC1C,IAAI,WACF,QAAQ,YAAY;CAGtB,MAAM,QAAQ,UAAU,UAAU;CAClC,IAAI,OACF,QAAQ,QAAQ;CAOlB,MAAM,mBAAmB,UAAU,qBAAqB;CACxD,IAAI,kBACF,QAAQ,mBAAmB;CAG7B,MAAM,uBAAuB,UAAU,yBAAyB;CAChE,IAAI,sBACF,QAAQ,uBAAuB;CAMjC,MAAM,kBAAkB,UAAU,oBAAoB;CACtD,IAAI,iBACF,QAAQ,kBAAkB;CAG5B,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/context/index.ts"],"sourcesContent":["/**\n * Context Module\n * Manages request-scoped context using AsyncLocalStorage\n * Thread-safe context propagation for async operations\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { getScopedWorkspaceContext } from '../prisma/workspace-extension.js';\nimport type { CfAccessCredentials, SDKContext } from '../types/index.js';\n\nconst asyncLocalStorage = new AsyncLocalStorage<SDKContext>();\n\n/**\n * A Cloudflare Access service token the service configured for itself, from its own\n * configuration (for example `CF_ACCESS_CLIENT_ID` / `CF_ACCESS_CLIENT_SECRET` in its\n * environment), via {@link ContextManager.configureCfAccessServiceToken}.\n *\n * This is the only process-wide Cloudflare Access state. It is never written from request\n * data: credentials an inbound request presented live only in that request's bound async\n * scope (see {@link ContextManager.getCfAccessHeaders}).\n */\nlet configuredServiceToken: { clientId: string; clientSecret: string } | undefined;\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\n/**\n * The Cloudflare Access credentials bound to the current async scope: the ContextManager\n * store first, then the request scope the SDK server binds for GraphQL execution and REST\n * handlers. Reads only bound stores, never the deprecated warn-mode workspace fallback.\n */\nfunction scopedCfAccess(): CfAccessCredentials | undefined {\n const context = asyncLocalStorage.getStore();\n const fromContext: CfAccessCredentials = {\n clientId: nonEmpty(context?.cfAccessClientId),\n clientSecret: nonEmpty(context?.cfAccessClientSecret),\n authorization: nonEmpty(context?.cfAuthorization),\n };\n const fromRequestScope = getScopedWorkspaceContext()?.cfAccess;\n const contextHasPair = Boolean(fromContext.clientId && fromContext.clientSecret);\n const scopeHasPair = Boolean(fromRequestScope?.clientId && fromRequestScope.clientSecret);\n // The service-token pair is taken from one source as a unit, never mixed across stores.\n const pair = contextHasPair ? fromContext : scopeHasPair ? fromRequestScope : undefined;\n const authorization = fromContext.authorization ?? nonEmpty(fromRequestScope?.authorization);\n if (!pair && !authorization) return undefined;\n return {\n ...(pair ? { clientId: pair.clientId, clientSecret: pair.clientSecret } : {}),\n ...(authorization ? { authorization } : {}),\n };\n}\n\n/** The service-token pair for the current scope, else the token the service configured. */\nfunction serviceTokenPair(\n scoped: CfAccessCredentials | undefined = scopedCfAccess()\n): { clientId: string; clientSecret: string } | undefined {\n if (scoped?.clientId && scoped.clientSecret) {\n return { clientId: scoped.clientId, clientSecret: scoped.clientSecret };\n }\n return configuredServiceToken;\n}\n\n/**\n * Context Manager for handling request-scoped context\n */\nexport class ContextManager {\n /**\n * Get current context from async local storage\n */\n public static getContext(): SDKContext | undefined {\n return asyncLocalStorage.getStore();\n }\n\n /**\n * Set context for current async scope\n * Merges with existing context if present\n */\n public static setContext(context: SDKContext): void {\n const currentContext = this.getContext() || {};\n asyncLocalStorage.enterWith({ ...currentContext, ...context });\n }\n\n /**\n * Configure a Cloudflare Access service token the service holds for itself, read from its own\n * configuration (never from a request). Cross-layer calls attach it when the current request\n * scope carries no service-token pair of its own, which lets background work (stream\n * consumers, schedulers, CLIs) pass a Cloudflare-Access-gated peer gateway.\n *\n * Pass both values to set the token, or call it with no arguments to remove it. A lone half\n * is ignored, since it can never pass Access.\n *\n * @example\n * ```typescript\n * ContextManager.configureCfAccessServiceToken(process.env.CF_ACCESS_CLIENT_ID, process.env.CF_ACCESS_CLIENT_SECRET);\n * ```\n */\n public static configureCfAccessServiceToken(clientId?: string, clientSecret?: string): void {\n const id = nonEmpty(clientId);\n const secret = nonEmpty(clientSecret);\n if (id && secret) {\n configuredServiceToken = { clientId: id, clientSecret: secret };\n } else if (id === undefined && secret === undefined) {\n configuredServiceToken = undefined;\n }\n }\n\n /**\n * @deprecated Use {@link ContextManager.configureCfAccessServiceToken} with the service's own\n * token. Credentials a request presents no longer need recording: the SDK server binds them\n * to that request's scope.\n *\n * Kept for services that seed their own token from configuration. It sets the service token\n * when both values are present and otherwise does nothing. The `CF_Authorization` cookie is a\n * per-user credential, so it is never stored process-wide and the third argument is ignored.\n */\n public static setCfAccessContext(clientId?: string, clientSecret?: string, _cfAuthorization?: string): void {\n if (nonEmpty(clientId) && nonEmpty(clientSecret)) {\n this.configureCfAccessServiceToken(clientId, clientSecret);\n }\n }\n\n /**\n * Run function with specific context\n * Context is isolated to this execution and its children\n */\n public static async withContext<T>(context: SDKContext, fn: () => Promise<T>): Promise<T> {\n return asyncLocalStorage.run(context, fn);\n }\n\n /**\n * Run synchronous function with specific context\n */\n public static withContextSync<T>(context: SDKContext, fn: () => T): T {\n return asyncLocalStorage.run(context, fn);\n }\n\n /**\n * Clear current context, including any configured Cloudflare Access service token.\n */\n public static clearContext(): void {\n asyncLocalStorage.disable();\n configuredServiceToken = undefined;\n }\n\n /**\n * Get actor ID from context\n */\n public static getActorId(): string | undefined {\n return this.getContext()?.actorId;\n }\n\n /**\n * Get legacy user ID from context.\n */\n public static getUser(): string | undefined {\n const context = this.getContext();\n const userId = context?.['userId'];\n return typeof userId === 'string' ? userId : context?.actorId;\n }\n\n /**\n * Get workspace ID from context\n */\n public static getWorkspace(): string | undefined {\n return this.getContext()?.workspaceId;\n }\n\n /**\n * Get tenant ID from context\n */\n public static getTenant(): string | undefined {\n return this.getContext()?.tenantId;\n }\n\n /**\n * Get legacy organization ID from context.\n */\n public static getOrganization(): string | undefined {\n const organizationId = this.getContext()?.['organizationId'];\n return typeof organizationId === 'string' ? organizationId : undefined;\n }\n\n /**\n * Get project ID from context\n */\n public static getProject(): string | undefined {\n return this.getContext()?.projectId;\n }\n\n /**\n * Get app ID from context\n */\n public static getApp(): string | undefined {\n return this.getContext()?.appId;\n }\n\n /**\n * Get JWT token from context\n */\n public static getToken(): string | undefined {\n return this.getContext()?.token;\n }\n\n /**\n * Get product ID from context\n */\n public static getProduct(): string | undefined {\n return this.getContext()?.productId;\n }\n\n /**\n * The Cloudflare Access service-token client id for the current request scope, else the\n * service's configured token. Undefined outside a bound scope unless a token is configured.\n */\n public static getCfAccessClientId(): string | undefined {\n return serviceTokenPair()?.clientId;\n }\n\n /**\n * The Cloudflare Access service-token client secret, resolved together with\n * {@link ContextManager.getCfAccessClientId}.\n */\n public static getCfAccessClientSecret(): string | undefined {\n return serviceTokenPair()?.clientSecret;\n }\n\n /**\n * The `CF_Authorization` cookie value the current request presented. Read only from the bound\n * request scope: it is a per-user credential and is never shared across requests.\n */\n public static getCfAuthorization(): string | undefined {\n return scopedCfAccess()?.authorization;\n }\n\n /**\n * Build the Cloudflare Access credentials to re-present on a cross-layer outbound call.\n *\n * Sources, in order:\n * 1. The credentials the current request presented, read only from its bound async scope\n * (the ContextManager store, or the request scope the SDK server binds for GraphQL\n * execution and REST handlers).\n * 2. For the service-token pair only, a token the service configured for itself with\n * {@link ContextManager.configureCfAccessServiceToken}.\n *\n * Fails closed: outside a bound request scope, and with no configured token, it returns `{}`.\n * Credentials one request presented are never attached to another request or to background\n * work. It is also `{}` wherever no Cloudflare Access fronts the gateways (local dev and\n * production).\n */\n public static getCfAccessHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n const scoped = scopedCfAccess();\n\n const pair = serviceTokenPair(scoped);\n if (pair) {\n headers['cf-access-client-id'] = pair.clientId;\n headers['cf-access-client-secret'] = pair.clientSecret;\n }\n\n // A real user request on alpha carries the CF_Authorization cookie rather than a service\n // token; re-present it as the cookie for this request only. See BOFF-2929.\n const cfAuthorization = scoped?.authorization;\n if (cfAuthorization) {\n headers['cookie'] = `CF_Authorization=${cfAuthorization}`;\n }\n\n return headers;\n }\n\n /**\n * Update specific context fields\n */\n public static updateContext(updates: Partial<SDKContext>): void {\n const current = this.getContext();\n if (current) {\n this.setContext({ ...current, ...updates });\n } else {\n this.setContext(updates);\n }\n }\n\n /**\n * Check if context exists\n */\n public static hasContext(): boolean {\n return this.getContext() !== undefined;\n }\n\n /**\n * Get custom field from context\n */\n public static getCustomField(key: string): unknown {\n return this.getContext()?.[key];\n }\n\n /**\n * Set custom field in context\n */\n public static setCustomField(key: string, value: unknown): void {\n const current = this.getContext() || {};\n this.setContext({ ...current, [key]: value });\n }\n}\n\n/**\n * Default export for convenience\n */\nexport const contextManager = ContextManager;\n\n/**\n * Helper function to extract context from HTTP request\n */\nexport function extractContextFromRequest(req: {\n headers: Record<string, string | string[] | undefined>;\n user?: { user_id?: string; workspace_id?: string; tenant_endpoint?: string };\n}): SDKContext {\n const context: SDKContext = {};\n\n // Extract from user object (if JWT already verified)\n if (req.user) {\n context.actorId = req.user.user_id;\n context.workspaceId = req.user.workspace_id;\n context.tenantId = req.user.tenant_endpoint;\n }\n\n // Extract from headers\n const getHeader = (key: string): string | undefined => {\n const value = req.headers[key.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n };\n\n const authHeader = getHeader('authorization');\n if (authHeader) {\n context.token = authHeader.replace('Bearer ', '');\n }\n\n const workspaceId = getHeader('x-workspace-id');\n if (workspaceId && !context.workspaceId) {\n context.workspaceId = workspaceId;\n }\n\n const productId = getHeader('x-product-id');\n if (productId) {\n context.productId = productId;\n }\n\n const projectId = getHeader('x-project-id');\n if (projectId) {\n context.projectId = projectId;\n }\n\n const appId = getHeader('x-app-id');\n if (appId) {\n context.appId = appId;\n }\n\n // Cloudflare Access service token. Forwarded to subgraphs by the public\n // gateways only when the request actually transited CF (cf-ray present), so\n // we can capture whatever arrives here. Re-presented on cross-layer outbound\n // calls — see ContextManager.getCfAccessHeaders.\n const cfAccessClientId = getHeader('cf-access-client-id');\n if (cfAccessClientId) {\n context.cfAccessClientId = cfAccessClientId;\n }\n\n const cfAccessClientSecret = getHeader('cf-access-client-secret');\n if (cfAccessClientSecret) {\n context.cfAccessClientSecret = cfAccessClientSecret;\n }\n\n // CF Access user-SSO cookie, forwarded by the public gateway as\n // x-cf-authorization. Re-presented as the CF_Authorization cookie on\n // cross-layer calls (see getCfAccessHeaders). See BOFF-2929.\n const cfAuthorization = getHeader('x-cf-authorization');\n if (cfAuthorization) {\n context.cfAuthorization = cfAuthorization;\n }\n\n return context;\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,oBAAoB,IAAI,kBAA8B;;;;;;;;;;AAW5D,IAAI;AAEJ,SAAS,SAAS,OAA+C;CAC/D,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;;;;;;AAOA,SAAS,iBAAkD;CACzD,MAAM,UAAU,kBAAkB,SAAS;CAC3C,MAAM,cAAmC;EACvC,UAAU,SAAS,SAAS,gBAAgB;EAC5C,cAAc,SAAS,SAAS,oBAAoB;EACpD,eAAe,SAAS,SAAS,eAAe;CAClD;CACA,MAAM,mBAAmB,0BAA0B,CAAC,EAAE;CACtD,MAAM,iBAAiB,QAAQ,YAAY,YAAY,YAAY,YAAY;CAC/E,MAAM,eAAe,QAAQ,kBAAkB,YAAY,iBAAiB,YAAY;CAExF,MAAM,OAAO,iBAAiB,cAAc,eAAe,mBAAmB;CAC9E,MAAM,gBAAgB,YAAY,iBAAiB,SAAS,kBAAkB,aAAa;CAC3F,IAAI,CAAC,QAAQ,CAAC,eAAe,OAAO;CACpC,OAAO;EACL,GAAI,OAAO;GAAE,UAAU,KAAK;GAAU,cAAc,KAAK;EAAa,IAAI,CAAC;EAC3E,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;CAC3C;AACF;;AAGA,SAAS,iBACP,SAA0C,eAAe,GACD;CACxD,IAAI,QAAQ,YAAY,OAAO,cAC7B,OAAO;EAAE,UAAU,OAAO;EAAU,cAAc,OAAO;CAAa;CAExE,OAAO;AACT;;;;AAKA,IAAa,iBAAb,MAA4B;;;;C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,SAAgB,0BAA0B,KAG3B;CACb,MAAM,UAAsB,CAAC;CAG7B,IAAI,IAAI,MAAM;EACZ,QAAQ,UAAU,IAAI,KAAK;EAC3B,QAAQ,cAAc,IAAI,KAAK;EAC/B,QAAQ,WAAW,IAAI,KAAK;CAC9B;CAGA,MAAM,aAAa,QAAoC;EACrD,MAAM,QAAQ,IAAI,QAAQ,IAAI,YAAY;EAC1C,OAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK;CAC3C;CAEA,MAAM,aAAa,UAAU,eAAe;CAC5C,IAAI,YACF,QAAQ,QAAQ,WAAW,QAAQ,WAAW,EAAE;CAGlD,MAAM,cAAc,UAAU,gBAAgB;CAC9C,IAAI,eAAe,CAAC,QAAQ,aAC1B,QAAQ,cAAc;CAGxB,MAAM,YAAY,UAAU,cAAc;CAC1C,IAAI,WACF,QAAQ,YAAY;CAGtB,MAAM,YAAY,UAAU,cAAc;CAC1C,IAAI,WACF,QAAQ,YAAY;CAGtB,MAAM,QAAQ,UAAU,UAAU;CAClC,IAAI,OACF,QAAQ,QAAQ;CAOlB,MAAM,mBAAmB,UAAU,qBAAqB;CACxD,IAAI,kBACF,QAAQ,mBAAmB;CAG7B,MAAM,uBAAuB,UAAU,yBAAyB;CAChE,IAAI,sBACF,QAAQ,uBAAuB;CAMjC,MAAM,kBAAkB,UAAU,oBAAoB;CACtD,IAAI,iBACF,QAAQ,kBAAkB;CAG5B,OAAO;AACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as WorkspaceMemberRemovedPayload, $t as IEventQueue, A as OrganizationDeletedPayload, At as EntityEventType, B as TaxonomyPublishMetadata, Bt as createGraphEventEmitter$1, C as EventsManagerSubscribeOptions, Ct as SubscribeOptions, D as EventSpec, Dt as ModuleEventsService, E as EVENT_TAXONOMY_BRAND, Et as ModuleEventsConfig, F as TaxonomyEventKind, Ft as resetGraphEventEmitter, G as VibecontrolsSessionStartedPayload, Gt as RedisStreamsEventConsumer, H as VibecontrolsAgentConnectedPayload, Ht as createMemoryPublisher, I as TaxonomyEventLayer, It as MemoryEventBus, J as WorkflowRunFailedPayload, Jt as EventQueueFactory, K as WSPACE_GRAPH_EVENTS_STREAM, Kt as RedisStreamsEventPublisher, L as TaxonomyEventPii, Lt as MemoryEventConsumer, M as PublishableEventName, Mt as GraphEventEmitterImpl, N as REFERENCE_PRODUCT_EVENT_TAXONOMY, Nt as createGraphEventEmitter, O as EventTaxonomy, Ot as createModuleEventsService, P as SubscriptionChangedPayload, Pt as getGraphEventEmitter, Q as WorkspaceMemberAddedPayload, Qt as PublishOptions, R as TaxonomyEventStatus, Rt as MemoryEventPublisher, S as EventsManagerStreamRoute, St as StreamInfo, T as DefinedEventTaxonomy, Tt as ModuleEventPayload, U as VibecontrolsAgentDisconnectedPayload, Ut as dlqKey, V as UserDeletedPayload, Vt as createMemoryConsumer, W as VibecontrolsSessionEndedPayload, Wt as streamKey, X as WorkspaceCreatedPayload, Xt as ISubscription, Y as WorkflowRunStartedPayload, Yt as IEventConsumer, Z as WorkspaceDeletedPayload, Zt as IEventPublisher, _ as EventsManager, _t as EventMessage$1, a as LifecycleEventContext, an as QueueType, at as publishTaxonomyEvent, b as EventsManagerOptions, bt as PublishEventOptions, c as OrganizationDeletedFact, cn as EventHandler, ct as EVENT_STREAMS_URL_ENV_KEYS, d as buildConsumerGroupName, dn as StreamConfig, dt as resolveEventStreamsUrl, en as BaseQueueConfig, et as WorkspaceMemberRoleUpdatedPayload, f as createLifecycleConsumer, fn as SubscriptionOptions, ft as resolveEventStreamsUrlSource, g as parseWorkspaceMemberRemoved, gt as createPublisher, h as parseWorkspaceDeletedStream, ht as createConsumer, i as LifecycleConsumerOptions, in as QueueStatistics, it as mergeEventTaxonomies, j as PLATFORM_EVENT_TAXONOMY, jt as GraphEventEmitter, k as GraphEntityEventPayload, kt as EntityEventRbacMetadata, l as WorkspaceDeletedFact, ln as EventMessage, lt as GRAPH_EVENTS_URL_ENV_KEYS, m as parseWorkspaceDeletedGraph, mt as resolveGraphEventsUrlSource, n as LIFECYCLE_SUBJECTS, nn as EventQueueHealthCheckResult, nt as eventSpec, o as LifecycleEventSource, on as AcknowledgeableEvent, ot as taxonomyEventNames, p as parseOrganizationDeleted, pt as resolveGraphEventsUrl, q as WorkflowRunCompletedPayload, qt as RedisStreamsConnection, r as LifecycleConsumer, rn as PublisherConfig, rt as isDefinedEventTaxonomy, s as LifecycleHandlers, sn as ConsumerOptions, st as taxonomyNameViolation, tn as ConsumerConfig, tt as defineEventTaxonomy, u as WorkspaceMemberRemovedFact, un as EventMetadata, ut as eventKeyScopeForUrl, v as EventsManagerHandler, vt as EventPriority, w as createEventsManagerSingleton, wt as BulkEventPayload, x as EventsManagerSingleton, xt as PublishResult, y as EventsManagerMessage, yt as EventsModule, z as TaxonomyPayload, zt as MemoryEventQueue } from "../index-
|
|
1
|
+
import { $ as WorkspaceMemberRemovedPayload, $t as IEventQueue, A as OrganizationDeletedPayload, At as EntityEventType, B as TaxonomyPublishMetadata, Bt as createGraphEventEmitter$1, C as EventsManagerSubscribeOptions, Ct as SubscribeOptions, D as EventSpec, Dt as ModuleEventsService, E as EVENT_TAXONOMY_BRAND, Et as ModuleEventsConfig, F as TaxonomyEventKind, Ft as resetGraphEventEmitter, G as VibecontrolsSessionStartedPayload, Gt as RedisStreamsEventConsumer, H as VibecontrolsAgentConnectedPayload, Ht as createMemoryPublisher, I as TaxonomyEventLayer, It as MemoryEventBus, J as WorkflowRunFailedPayload, Jt as EventQueueFactory, K as WSPACE_GRAPH_EVENTS_STREAM, Kt as RedisStreamsEventPublisher, L as TaxonomyEventPii, Lt as MemoryEventConsumer, M as PublishableEventName, Mt as GraphEventEmitterImpl, N as REFERENCE_PRODUCT_EVENT_TAXONOMY, Nt as createGraphEventEmitter, O as EventTaxonomy, Ot as createModuleEventsService, P as SubscriptionChangedPayload, Pt as getGraphEventEmitter, Q as WorkspaceMemberAddedPayload, Qt as PublishOptions, R as TaxonomyEventStatus, Rt as MemoryEventPublisher, S as EventsManagerStreamRoute, St as StreamInfo, T as DefinedEventTaxonomy, Tt as ModuleEventPayload, U as VibecontrolsAgentDisconnectedPayload, Ut as dlqKey, V as UserDeletedPayload, Vt as createMemoryConsumer, W as VibecontrolsSessionEndedPayload, Wt as streamKey, X as WorkspaceCreatedPayload, Xt as ISubscription, Y as WorkflowRunStartedPayload, Yt as IEventConsumer, Z as WorkspaceDeletedPayload, Zt as IEventPublisher, _ as EventsManager, _t as EventMessage$1, a as LifecycleEventContext, an as QueueType, at as publishTaxonomyEvent, b as EventsManagerOptions, bt as PublishEventOptions, c as OrganizationDeletedFact, cn as EventHandler, ct as EVENT_STREAMS_URL_ENV_KEYS, d as buildConsumerGroupName, dn as StreamConfig, dt as resolveEventStreamsUrl, en as BaseQueueConfig, et as WorkspaceMemberRoleUpdatedPayload, f as createLifecycleConsumer, fn as SubscriptionOptions, ft as resolveEventStreamsUrlSource, g as parseWorkspaceMemberRemoved, gt as createPublisher, h as parseWorkspaceDeletedStream, ht as createConsumer, i as LifecycleConsumerOptions, in as QueueStatistics, it as mergeEventTaxonomies, j as PLATFORM_EVENT_TAXONOMY, jt as GraphEventEmitter, k as GraphEntityEventPayload, kt as EntityEventRbacMetadata, l as WorkspaceDeletedFact, ln as EventMessage, lt as GRAPH_EVENTS_URL_ENV_KEYS, m as parseWorkspaceDeletedGraph, mt as resolveGraphEventsUrlSource, n as LIFECYCLE_SUBJECTS, nn as EventQueueHealthCheckResult, nt as eventSpec, o as LifecycleEventSource, on as AcknowledgeableEvent, ot as taxonomyEventNames, p as parseOrganizationDeleted, pt as resolveGraphEventsUrl, q as WorkflowRunCompletedPayload, qt as RedisStreamsConnection, r as LifecycleConsumer, rn as PublisherConfig, rt as isDefinedEventTaxonomy, s as LifecycleHandlers, sn as ConsumerOptions, st as taxonomyNameViolation, tn as ConsumerConfig, tt as defineEventTaxonomy, u as WorkspaceMemberRemovedFact, un as EventMetadata, ut as eventKeyScopeForUrl, v as EventsManagerHandler, vt as EventPriority, w as createEventsManagerSingleton, wt as BulkEventPayload, x as EventsManagerSingleton, xt as PublishResult, y as EventsManagerMessage, yt as EventsModule, z as TaxonomyPayload, zt as MemoryEventQueue } from "../index-CGPNFIR3.js";
|
|
2
2
|
export { type AcknowledgeableEvent, type BaseQueueConfig, type BulkEventPayload, type ConsumerConfig, type ConsumerOptions, type DefinedEventTaxonomy, EVENT_STREAMS_URL_ENV_KEYS, EVENT_TAXONOMY_BRAND, type EntityEventRbacMetadata, type EntityEventType, type EventHandler, type EventMessage, type EventMetadata, EventPriority, EventQueueFactory, type EventQueueHealthCheckResult, type EventQueueHealthCheckResult as HealthCheckResult, type EventSpec, type EventTaxonomy, EventsManager, type EventsManagerHandler, type EventsManagerMessage, type EventsManagerOptions, type EventsManagerSingleton, type EventsManagerStreamRoute, type EventsManagerSubscribeOptions, EventsModule, GRAPH_EVENTS_URL_ENV_KEYS, type GraphEntityEventPayload, type GraphEventEmitter, GraphEventEmitterImpl, type EventMessage$1 as GraphQLEventMessage, type IEventConsumer, type IEventPublisher, type IEventQueue, type ISubscription, LIFECYCLE_SUBJECTS, type LifecycleConsumer, type LifecycleConsumerOptions, type LifecycleEventContext, type LifecycleEventSource, type LifecycleHandlers, MemoryEventBus, MemoryEventConsumer, MemoryEventPublisher, MemoryEventQueue, type ModuleEventPayload, type ModuleEventsConfig, ModuleEventsService, type OrganizationDeletedFact, type OrganizationDeletedPayload, PLATFORM_EVENT_TAXONOMY, type PublishEventOptions, type PublishOptions, type PublishResult, type PublishableEventName, type PublisherConfig, type QueueStatistics, QueueType, REFERENCE_PRODUCT_EVENT_TAXONOMY, RedisStreamsConnection, RedisStreamsEventConsumer, RedisStreamsEventPublisher, type StreamConfig, type StreamInfo, type SubscribeOptions, type SubscriptionChangedPayload, type SubscriptionOptions, type TaxonomyEventKind, type TaxonomyEventLayer, type TaxonomyEventPii, type TaxonomyEventStatus, type TaxonomyPayload, type TaxonomyPublishMetadata, type UserDeletedPayload, type VibecontrolsAgentConnectedPayload, type VibecontrolsAgentDisconnectedPayload, type VibecontrolsSessionEndedPayload, type VibecontrolsSessionStartedPayload, WSPACE_GRAPH_EVENTS_STREAM, type WorkflowRunCompletedPayload, type WorkflowRunFailedPayload, type WorkflowRunStartedPayload, type WorkspaceCreatedPayload, type WorkspaceDeletedFact, type WorkspaceDeletedPayload, type WorkspaceMemberAddedPayload, type WorkspaceMemberRemovedFact, type WorkspaceMemberRemovedPayload, type WorkspaceMemberRoleUpdatedPayload, buildConsumerGroupName, createConsumer, createEventsManagerSingleton, createGraphEventEmitter, createLifecycleConsumer, createMemoryConsumer, createGraphEventEmitter$1 as createMemoryGraphEventEmitter, createMemoryPublisher, createModuleEventsService, createPublisher, defineEventTaxonomy, eventKeyScopeForUrl, eventSpec, getGraphEventEmitter, isDefinedEventTaxonomy, mergeEventTaxonomies, parseOrganizationDeleted, parseWorkspaceDeletedGraph, parseWorkspaceDeletedStream, parseWorkspaceMemberRemoved, publishTaxonomyEvent, dlqKey as redisDlqKey, streamKey as redisStreamKey, resetGraphEventEmitter, resolveEventStreamsUrl, resolveEventStreamsUrlSource, resolveGraphEventsUrl, resolveGraphEventsUrlSource, taxonomyEventNames, taxonomyNameViolation };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as FeatureFlagProvider, c as FlagEvaluation, i as createOperationsFlagGatePlugin, l as FlagType, n as GatedOperationType, o as EvaluationContext, r as OperationsFlagGatePluginOptions, s as FeatureFlagProviderConfig, u as ResolutionDetails } from "../index-
|
|
1
|
+
import { a as FeatureFlagProvider, c as FlagEvaluation, i as createOperationsFlagGatePlugin, l as FlagType, n as GatedOperationType, o as EvaluationContext, r as OperationsFlagGatePluginOptions, s as FeatureFlagProviderConfig, u as ResolutionDetails } from "../index-B-yXdMeb.js";
|
|
2
2
|
export { type EvaluationContext, FeatureFlagProvider, type FeatureFlagProviderConfig, type FlagEvaluation, type FlagType, type GatedOperationType, type OperationsFlagGatePluginOptions, type ResolutionDetails, createOperationsFlagGatePlugin };
|
package/dist/graph/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { _ as SearchResponse, a as EdgeDocument, c as EntityVertex, d as ModuleGraphConfig, f as ProductFacet, g as SearchFilters, h as SearchFacets, i as addGraphExtension, l as GraphEvent, m as RelationshipGraphConfig, n as GraphEventEmitter, o as EntityBulkOperationsConfig, r as GraphMiddlewareConfig, s as EntityGraphConfig, t as EntityEventType, u as GraphEventType, v as SearchResult, y as TypeFacet } from "../prisma-extension-Cfl09swM.js";
|
|
2
|
-
import { $ as createGraphEventsHelper, A as GraphSchema, B as GraphExportService, C as defineGraphConfig, Ct as shouldSyncRelationship, D as EntityEventHook, E as EntityEventContext, F as RelationshipExportData, G as createRelationshipFromEntity, H as GraphRelationshipExport, I as defineModuleGraph, J as GraphEventPublishOptions, K as EntityEventData, L as EntityFetcher, M as ModuleGraphDefinition, N as RelationshipDefinition, O as EntityRbacConfig, P as RelationshipEventData, Q as GraphRelationshipData, R as GraphEntityExport, S as defineEntity, St as shouldSyncEntity, T as EntityDefinition, U as RelationshipFetcher, V as GraphExportServiceConfig, W as createGraphExportService, X as GraphEventsHelperConfig, Y as GraphEventsHelper, Z as GraphEventsPublisher, _ as DefineGraphConfigOptions, _t as createRelationshipEvent, a as GraphNode, at as createPrismaGraphIntegration, b as STANDARD_FIELDS, bt as getCollectionForEntity, c as TraverseOptions, ct as ExtractedRelationshipData, d as InitializeGraphOptions, dt as GenericGraphConfig, et as getGraphEventsPublisher, f as getGraphStats, ft as GenericRelationshipConfig, g as DefineEntityConfigOptions, gt as createEntityEvent, h as AUDIT_FIELDS, ht as ValidationErrorType, i as GraphModule, it as PrismaGraphIntegrationOptions, j as ModuleGraph, k as GraphEventOptions, l as TraverseResult, lt as FieldMapper, m as isGraphInitialized, mt as GraphValidationResult, n as CreateNodeOptions, nt as withDeferredGraphEvents, o as QueryGraphOptions, ot as EntityRbacConfig$1, p as initializeGraph, pt as GraphValidationError, q as GraphEntityConfig, r as GraphEdge, rt as PrismaGraphIntegration, s as TraverseDirection, st as ExtractedEntityData, t as CreateEdgeOptions, tt as DeferredGraphResult, ut as GenericEntityConfig, v as DefineRelationshipConfigOptions, vt as extractEntityTitle, w as defineRelationship, wt as GraphRegistry, x as TENANT_FIELDS, xt as parseRelationship, y as SOFT_DELETE_FIELDS, yt as extractMinimalFields, z as GraphExportResponse } from "../index-
|
|
2
|
+
import { $ as createGraphEventsHelper, A as GraphSchema, B as GraphExportService, C as defineGraphConfig, Ct as shouldSyncRelationship, D as EntityEventHook, E as EntityEventContext, F as RelationshipExportData, G as createRelationshipFromEntity, H as GraphRelationshipExport, I as defineModuleGraph, J as GraphEventPublishOptions, K as EntityEventData, L as EntityFetcher, M as ModuleGraphDefinition, N as RelationshipDefinition, O as EntityRbacConfig, P as RelationshipEventData, Q as GraphRelationshipData, R as GraphEntityExport, S as defineEntity, St as shouldSyncEntity, T as EntityDefinition, U as RelationshipFetcher, V as GraphExportServiceConfig, W as createGraphExportService, X as GraphEventsHelperConfig, Y as GraphEventsHelper, Z as GraphEventsPublisher, _ as DefineGraphConfigOptions, _t as createRelationshipEvent, a as GraphNode, at as createPrismaGraphIntegration, b as STANDARD_FIELDS, bt as getCollectionForEntity, c as TraverseOptions, ct as ExtractedRelationshipData, d as InitializeGraphOptions, dt as GenericGraphConfig, et as getGraphEventsPublisher, f as getGraphStats, ft as GenericRelationshipConfig, g as DefineEntityConfigOptions, gt as createEntityEvent, h as AUDIT_FIELDS, ht as ValidationErrorType, i as GraphModule, it as PrismaGraphIntegrationOptions, j as ModuleGraph, k as GraphEventOptions, l as TraverseResult, lt as FieldMapper, m as isGraphInitialized, mt as GraphValidationResult, n as CreateNodeOptions, nt as withDeferredGraphEvents, o as QueryGraphOptions, ot as EntityRbacConfig$1, p as initializeGraph, pt as GraphValidationError, q as GraphEntityConfig, r as GraphEdge, rt as PrismaGraphIntegration, s as TraverseDirection, st as ExtractedEntityData, t as CreateEdgeOptions, tt as DeferredGraphResult, ut as GenericEntityConfig, v as DefineRelationshipConfigOptions, vt as extractEntityTitle, w as defineRelationship, wt as GraphRegistry, x as TENANT_FIELDS, xt as parseRelationship, y as SOFT_DELETE_FIELDS, yt as extractMinimalFields, z as GraphExportResponse } from "../index-DYKWUbL4.js";
|
|
3
3
|
export { AUDIT_FIELDS, CreateEdgeOptions, CreateNodeOptions, type DeferredGraphResult, type DefineEntityConfigOptions, type DefineGraphConfigOptions, type DefineRelationshipConfigOptions, type EdgeDocument, type EntityBulkOperationsConfig, type EntityDefinition, type EntityEventContext, type EntityEventData, type EntityEventHook, type EntityEventType, type EntityFetcher, type EntityGraphConfig, type EntityRbacConfig, type EntityVertex, type ExtractedEntityData, type ExtractedRelationshipData, type FieldMapper, type GenericEntityConfig, type EntityRbacConfig$1 as GenericEntityRbacConfig, type GenericGraphConfig, type GenericRelationshipConfig, GraphEdge, type GraphEntityConfig, type GraphEntityExport, type GraphEvent, type GraphEventEmitter, type GraphEventOptions, type GraphEventPublishOptions, type GraphEventType, type GraphEventsHelper, type GraphEventsHelperConfig, GraphEventsPublisher, type GraphExportResponse, GraphExportService, type GraphExportServiceConfig, type GraphMiddlewareConfig, GraphModule, GraphNode, GraphRegistry, type GraphRelationshipData, type GraphRelationshipExport, type GraphSchema, type GraphValidationError, type GraphValidationResult, type InitializeGraphOptions, type ModuleGraph, type ModuleGraphConfig, type ModuleGraphDefinition, type PrismaGraphIntegration, type PrismaGraphIntegrationOptions, type ProductFacet, QueryGraphOptions, type RelationshipDefinition, type RelationshipEventData, type RelationshipExportData, type RelationshipFetcher, type RelationshipGraphConfig, SOFT_DELETE_FIELDS, STANDARD_FIELDS, type SearchFacets, type SearchFilters, type SearchResponse, type SearchResult, TENANT_FIELDS, TraverseDirection, TraverseOptions, TraverseResult, type TypeFacet, type ValidationErrorType, addGraphExtension, createEntityEvent, createGraphEventsHelper, createGraphExportService, createPrismaGraphIntegration, createRelationshipEvent, createRelationshipFromEntity, defineEntity, defineGraphConfig, defineModuleGraph, defineRelationship, extractEntityTitle, extractMinimalFields, getCollectionForEntity, getGraphEventsPublisher, getGraphStats, initializeGraph, isGraphInitialized, parseRelationship, shouldSyncEntity, shouldSyncRelationship, withDeferredGraphEvents };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { E as YogaPlugin } from "./types-
|
|
2
|
-
import "./index-
|
|
1
|
+
import { E as YogaPlugin } from "./types-IXZyPJCR.js";
|
|
2
|
+
import "./index-cPPtZTJh.js";
|
|
3
3
|
type FlagType = 'BOOLEAN' | 'STRING' | 'NUMBER' | 'JSON';
|
|
4
4
|
interface EvaluationContext {
|
|
5
5
|
actorId?: string;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { S as PrismaClientConfig, _ as installAcquireRetry, a as PrismaEvent, b as ConnectionState, c as PrismaLogLevel, d as configurePrismaLogging, f as createConnectionPool, g as fingerprintSqlQuery, h as ensureServiceApplicationName, i as PrismaClientWrapper, l as PrismaQueryEvent, m as createPrismaClient, n as PrismaClientBase, o as PrismaLogDefinition, p as createPrismaAdapter, r as PrismaClientConstructorOptions, s as PrismaLogEvent, t as DatabaseReturnType, u as PrismaTransactionOptions, v as isTransientAcquireError, x as DatabaseHealth, y as normalizeSqlTemplate } from "./client-NknQrWsP.js";
|
|
2
2
|
import { n as GraphEventEmitter } from "./prisma-extension-Cfl09swM.js";
|
|
3
|
-
import { A as withSystemScopeSync, C as requireWorkspaceContext, D as runOperationWithRlsGuc, E as runOperationInCallerTransaction, M as withWorkspaceContextSync, O as setWorkspaceContext, S as maybeTagConnection, T as resetWorkspaceContextStateForTests, _ as getWorkspaceContextFallbackMode, a as WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, b as isSystemScope, c as WorkspaceExtensionConfig, d as configureWorkspaceContextFallback, f as defaultWorkspaceExtensionConfig, g as getWorkspaceContext, h as getScopedWorkspaceContext, i as TransactionContextStatement, j as withWorkspaceContext, k as withSystemScope, l as addWorkspaceExtension, m as getCallerTransaction, n as PrismaQueryInternalParams, o as WorkspaceContext, p as explicitWorkspaceIdFromArgs, r as RawPrismaForCallerTransaction, s as WorkspaceContextFallbackMode, t as CallerTransaction, u as buildTransactionContextStatement, v as injectCreateFields, w as resetCallerTransactionStateForTests, x as maybeSetRlsGuc, y as injectWhereWorkspaceId } from "./workspace-extension-
|
|
3
|
+
import { A as withSystemScopeSync, C as requireWorkspaceContext, D as runOperationWithRlsGuc, E as runOperationInCallerTransaction, M as withWorkspaceContextSync, O as setWorkspaceContext, S as maybeTagConnection, T as resetWorkspaceContextStateForTests, _ as getWorkspaceContextFallbackMode, a as WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, b as isSystemScope, c as WorkspaceExtensionConfig, d as configureWorkspaceContextFallback, f as defaultWorkspaceExtensionConfig, g as getWorkspaceContext, h as getScopedWorkspaceContext, i as TransactionContextStatement, j as withWorkspaceContext, k as withSystemScope, l as addWorkspaceExtension, m as getCallerTransaction, n as PrismaQueryInternalParams, o as WorkspaceContext, p as explicitWorkspaceIdFromArgs, r as RawPrismaForCallerTransaction, s as WorkspaceContextFallbackMode, t as CallerTransaction, u as buildTransactionContextStatement, v as injectCreateFields, w as resetCallerTransactionStateForTests, x as maybeSetRlsGuc, y as injectWhereWorkspaceId } from "./workspace-extension-C0qib11C.js";
|
|
4
4
|
interface DatabaseClientConfig extends PrismaClientConfig {
|
|
5
5
|
productName: string;
|
|
6
6
|
enableGraphExtension?: boolean;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as BurdenoffGraphQLClient } from "./graphql-
|
|
2
|
-
import {
|
|
1
|
+
import { t as BurdenoffGraphQLClient } from "./graphql-DcZAKC6p.js";
|
|
2
|
+
import { m as SDKContext } from "./index-CQ3vxT5P.js";
|
|
3
3
|
declare namespace tenant_notifications_d_exports {
|
|
4
4
|
export { BatchNotificationInput, Notification$1 as Notification, NotificationChannel$1 as NotificationChannel, NotificationPriority, NotificationStats, NotificationTemplate, NotificationType$1 as NotificationType, RecipientInput$1 as RecipientInput, SendNotificationInput, SendWithTemplateInput, TenantNotificationsModule };
|
|
5
5
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { m as ServiceLayer } from "./layer-C0zxAUgR.js";
|
|
2
2
|
import { n as ShutdownDisposable } from "./index-Dt1HJPTX.js";
|
|
3
|
-
import { t as BurdenoffGraphQLClient } from "./graphql-
|
|
4
|
-
import {
|
|
3
|
+
import { t as BurdenoffGraphQLClient } from "./graphql-DcZAKC6p.js";
|
|
4
|
+
import { m as SDKContext } from "./index-CQ3vxT5P.js";
|
|
5
5
|
interface EventMessage$1<T = unknown> {
|
|
6
6
|
id: string;
|
|
7
7
|
subject: string;
|
|
@@ -29,6 +29,11 @@ interface LoggerTransport {
|
|
|
29
29
|
log(level: string, message: string, meta?: Record<string, unknown>): void;
|
|
30
30
|
}
|
|
31
31
|
type ActorType = 'user' | 'app' | 'service' | 'super_admin';
|
|
32
|
+
interface CfAccessCredentials {
|
|
33
|
+
clientId?: string;
|
|
34
|
+
clientSecret?: string;
|
|
35
|
+
authorization?: string;
|
|
36
|
+
}
|
|
32
37
|
interface SDKContext {
|
|
33
38
|
actorId?: string;
|
|
34
39
|
actorType?: ActorType;
|
|
@@ -99,4 +104,4 @@ interface SDKShutdownOptions {
|
|
|
99
104
|
timeout?: number;
|
|
100
105
|
force?: boolean;
|
|
101
106
|
}
|
|
102
|
-
export {
|
|
107
|
+
export { SDKShutdownOptions as _, EventQueueHealthStatus as a, ValidationError as b, LoggerTransport as c, QuotaExceededError as d, RetryConfig as f, SDKHealthStatus as g, SDKError as h, CfAccessCredentials as i, NetworkError as l, SDKContext as m, ActorType as n, EventQueueSDKConfig as o, SDKConfig as p, AuthenticationError as r, LoggerConfig as s, APIError as t, PermissionDeniedError as u, TemporalHealthStatus as v, TimeoutError as y };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { m as SDKContext } from "./index-CQ3vxT5P.js";
|
|
2
2
|
declare namespace index_d_exports {
|
|
3
3
|
export { LogLevel, LogMeta, Logger, LoggerConfig, LoggerTransport, debug, error, log, logger, redactSensitiveFields, redactSensitiveString, warn };
|
|
4
4
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { t as BurdenoffGraphQLClient } from "./graphql-
|
|
2
|
-
import {
|
|
1
|
+
import { t as BurdenoffGraphQLClient } from "./graphql-DcZAKC6p.js";
|
|
2
|
+
import { m as SDKContext } from "./index-CQ3vxT5P.js";
|
|
3
3
|
import { ActivitySeverity, ActivityType } from "./activity/index.js";
|
|
4
|
-
import { p as UsageMetricType } from "./index-
|
|
5
|
-
import { a as NotificationType } from "./index-
|
|
4
|
+
import { p as UsageMetricType } from "./index-UQSbAERe.js";
|
|
5
|
+
import { a as NotificationType } from "./index-C96mNrLW.js";
|
|
6
6
|
import { o as AssistantSessionAttribution } from "./assistant-session-DA5ZKJOr.js";
|
|
7
7
|
interface TrackingEvent {
|
|
8
8
|
eventType: string;
|