@burdenoff/be-sdk 2026.718.1 → 2026.721.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/graph/index.ts","../src/graph/utils/prisma-helpers.ts","../src/graph/events-helper.ts","../src/graph/export-service.ts","../src/graph/module-graph.ts","../src/graph/config/builder.ts","../src/graph/config/init.ts"],"names":["createPrismaGraphIntegration","options","serviceName","graphConfig","productName","validateRuntime","process","env","NODE_ENV","autoInit","createPrismaClient","ensureServiceApplicationName","state","graphEmitter","extendedPrismaClient","emitterInitialized","initializationPromise","initializeGraphEmitter","logger","info","GraphEventEmitterImpl","basePrisma","initializeGraph","eventEmitter","enabled","error","db","warn","baseClient","client","prisma","Proxy","get","_","prop","value","bind","cleanup","disconnect","$disconnect","getGraphEmitter","isInitialized","GraphEventsPublisher","instance","initialized","emitter","getInstance","setProductName","name","initialize","getGraphEventEmitter","natsUrl","ensureInitialized","publishEntityCreated","entity","publishEntityEvent","publishEntityUpdated","publishEntityDeleted","publishRelationshipCreated","relationship","organizationId","publishRelationshipEvent","publishRelationshipDeleted","eventType","id","type","data","workspaceId","actorId","userId","debug","from","to","relationType","metadata","shutdown","reset","getGraphEventsPublisher","createGraphEventsHelper","config","publisher","moduleName","helper","entityConfig","Object","entries","entities","created","getOrgId","getWorkspaceId","onCreated","updated","onUpdated","deleted","onDeleted","GraphExportService","fetchers","relationshipFetchers","customTransformer","serviceConfig","transformEntity","getSchema","relationships","entityType","fields","Array","isArray","collection","relType","fromType","toType","edgeType","label","exportEntities","entityTypes","result","typesToExport","keys","fetcher","map","item","exportRelationships","rels","push","exportAll","schema","entityCounts","totalEntities","items","length","productSource","exportedAt","Date","toISOString","stats","totalRelationships","createdAt","updatedAt","tenantId","String","createGraphExportService","createRelationshipFromEntity","relationConfig","fromId","toId","extractMetadata","GraphEventsPublisherInternal","rbac","hasRbac","defineModuleGraph","definition","events","entityName","entityDef","undefined","createEventContext","publishRelationship","orgId","deleteRelationship","buildRbacMetadata","rbacConfig","createResource","entityId","title","resourceTypeName","extractName","identifier","extractIdentifier","parentResourceIdentifier","parentResourceField","entitySchema","relationshipSchema","relName","relDef","includes","fetch","ws","entitiesData","relationshipsData","getPublisher","STANDARD_FIELDS","SOFT_DELETE_FIELDS","AUDIT_FIELDS","TENANT_FIELDS","DEFAULT_GET_WORKSPACE_ID","DEFAULT_GET_ORG_ID","context","createDefaultExtractTitle","toLowerCase","generateRelationshipLabel","relationshipName","replace","toUpperCase","extractFieldsFromModel","modelName","prismaFieldsModule","hasModel","availableModels","getAllModelNames","join","Error","allFields","getScalarFields","sdkDefaults","softDelete","multiTenant","audit","excluded","Set","exclude","filteredFields","filter","field","has","finalFields","include","validateEntityConfig","errors","message","validateRelationshipConfig","relationshipKey","polymorphicTypeField","fromField","validateWorkspaceBoundary","_entityTypes","warnings","rootTypes","hasWorkspaceLink","relConfig","validateNoDuplicates","seenEntityTypes","relationshipLabels","add","key","validateGraphConfig","allErrors","allWarnings","relationshipConfig","boundaryResult","duplicateResult","valid","processEntityConfig","entityOptions","model","extractTitle","rest","entityFields","autoFields","mergedFields","finalGetWorkspaceId","_data","finalGetOrgId","processRelationships","relationshipOptions","toField","logValidationResults","validationResult","warning","errorCount","warningCount","autoFieldsApplied","defineGraphConfig","autoRegisterWithRegistry","registryEntities","registryRelationships","description","GraphRegistry","registerModule","defineEntity","defineRelationship","RuntimeValidator","validateEntityData","prismaClient","monitoredEntityTypes","shouldValidate","registerConfigWithRegistry","validator","wrappedEmitter","validation","extendedClient","addGraphExtension","isGraphInitialized","registeredModules","getRegisteredModules","getGraphStats","getStats","modules","GraphModule","createNode","ValidationError","properties","mutation","variables","input","response","query","nodeId","createGraphNode","createEdge","edgeId","createGraphEdge","getNode","getGraphNode","updateNode","updateGraphNode","deleteNode","deleteEdge","traverse","startNode","direction","edgeTypes","minDepth","maxDepth","limit","traverseGraph","findShortestPath","fromNode","toNode","bindVars","executeCypher","results","getNeighbors","getNodeDegree","findNodes","filters","offset","findGraphNodes","createNodesBatch","nodes","count","createGraphNodesBatch","createEdgesBatch","edges","createGraphEdgesBatch"],"mappings":";;;;;;;AAAA,IAAA,aAAA,GAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACoJO,SAASA,6BACdC,OAAAA,EAAqD;AASrD,EAAA,MAAM,EACJC,WAAAA,EACAC,WAAAA,EACAC,WAAAA,GAAc,YAAA,EACdC,eAAAA,GAAkBC,OAAAA,CAAQC,GAAAA,CAAIC,QAAAA,KAAa,YAAA,EAC3CC,QAAAA,GAAW,IAAA,EACXC,oBAAkB,GAChBT,OAAAA;AAOJU,EAAAA,4BAAAA,CAA6BP,WAAAA,CAAAA;AAG7B,EAAA,MAAMQ,KAAAA,GAA8C;IAClDC,YAAAA,EAAc,IAAA;IACdC,oBAAAA,EAAsB,IAAA;IACtBC,kBAAAA,EAAoB,KAAA;IACpBC,qBAAAA,EAAuB;AACzB,GAAA;AAUA,EAAA,eAAeC,sBAAAA,GAAAA;AAEb,IAAA,IAAIL,MAAMI,qBAAAA,EAAuB;AAC/B,MAAA,OAAOJ,KAAAA,CAAMI,qBAAAA;AACf,IAAA;AAGA,IAAA,IAAIJ,MAAMG,kBAAAA,EAAoB;AAC5B,MAAA;AACF,IAAA;AAGAH,IAAAA,KAAAA,CAAMI,yBAAyB,YAAA;AAC7B,MAAA,IAAI,CAACV,QAAQC,GAAAA,CAAI,sBAAA,KAA2BD,OAAAA,CAAQC,GAAAA,CAAI,sBAAA,CAAA,KAA4B,MAAA,EAAQ;AAC1FW,QAAAA,MAAAA,CAAOC,IAAAA,CAAK,CAAA,CAAA,EAAIjB,WAAAA,CAAAA,uBAAAA,CAAoC,CAAA;AACpDU,QAAAA,KAAAA,CAAMG,kBAAAA,GAAqB,IAAA;AAC3B,QAAA;AACF,MAAA;AAEA,MAAA,IAAI;AAEF,QAAA,IAAI,CAACT,QAAQC,GAAAA,CAAI,cAAA,KAAm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MAAM,8BAAA,EAAgC;AAAEmQ,MAAAA,KAAAA,EAAOG,KAAAA,CAAM3M;KAAO,CAAA;AAEnE,IAAA,MAAMkK,QAAAA,GAAW;;;;;;;;;;;;;;AAejB,IAAA,MAAMG,QAAAA,GAAW,MAAM,IAAA,CAAKzQ,MAAAA,CAAO0Q,MAA8CJ,QAAAA,EAAU;AAAEyC,MAAAA;AAAM,KAAA,EAAG,KAAKlJ,OAAO,CAAA;AAElHxK,IAAAA,MAAAA,CAAOC,KAAK,6BAAA,EAA+B;AAAEsT,MAAAA,KAAAA,EAAOnC,SAASuC,qBAAAA,CAAsB5M;KAAO,CAAA;AAE1F,IAAA,OAAOqK,QAAAA,CAASuC,qBAAAA;AAClB,EAAA;AACF","file":"chunk-V4QNOY4E.js","sourcesContent":["/**\n * Graph Integration Module\n *\n * All operations route through the federated GraphQL schema exposed by\n * `wspace-graph-svc` (via `wspace-int-gateway`). Consuming services never\n * open a direct graph-DB connection — the underlying graph database\n * cluster is only reached through the Python sidecar inside the graph pod.\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\nexport interface GraphNode {\n id: string;\n type: string;\n properties: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface GraphEdge {\n id: string;\n from: string;\n to: string;\n type: string;\n properties?: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n createdAt: string;\n}\n\nexport interface CreateNodeOptions {\n type: string;\n properties: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n}\n\nexport interface CreateEdgeOptions {\n from: string;\n to: string;\n type: string;\n properties?: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n}\n\n/**\n * Graph traversal direction\n */\nexport type TraverseDirection = 'outbound' | 'inbound' | 'any';\n\nexport interface TraverseOptions {\n startNode: string;\n direction?: TraverseDirection;\n edgeTypes?: string[];\n minDepth?: number;\n maxDepth?: number;\n limit?: number;\n}\n\nexport interface TraverseResult {\n nodes: GraphNode[];\n edges: GraphEdge[];\n paths: Array<{\n nodes: GraphNode[];\n edges: GraphEdge[];\n }>;\n}\n\nexport interface QueryGraphOptions {\n /** openCypher query (since the 2026-05 NebulaGraph → Apache AGE migration) */\n query: string;\n /** Bind variables */\n bindVars?: Record<string, unknown>;\n /** Limit results */\n limit?: number;\n}\n\n/**\n * Graph Integration Module\n */\nexport class GraphModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Create graph node\n */\n public async createNode(options: CreateNodeOptions): Promise<GraphNode> {\n if (!options.type) {\n throw new ValidationError('Node type is required');\n }\n\n if (!options.properties || typeof options.properties !== 'object') {\n throw new ValidationError('Node properties must be an object');\n }\n\n logger.debug('[Graph] Creating node', { type: options.type });\n\n const mutation = `\n mutation CreateGraphNode($input: CreateGraphNodeInput!) {\n createGraphNode(input: $input) {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n }\n `;\n\n const variables = {\n input: {\n type: options.type,\n properties: options.properties,\n workspaceId: options.workspaceId || this.context.workspaceId,\n organizationId: options.organizationId,\n },\n };\n\n const response = await this.client.query<{ createGraphNode: GraphNode }>(mutation, variables, this.context);\n\n logger.info('[Graph] Node created', { nodeId: response.createGraphNode.id });\n\n return response.createGraphNode;\n }\n\n /**\n * Create graph edge\n */\n public async createEdge(options: CreateEdgeOptions): Promise<GraphEdge> {\n if (!options.from) {\n throw new ValidationError('Source node ID is required');\n }\n\n if (!options.to) {\n throw new ValidationError('Target node ID is required');\n }\n\n if (!options.type) {\n throw new ValidationError('Edge type is required');\n }\n\n logger.debug('[Graph] Creating edge', {\n from: options.from,\n to: options.to,\n type: options.type,\n });\n\n const mutation = `\n mutation CreateGraphEdge($input: CreateGraphEdgeInput!) {\n createGraphEdge(input: $input) {\n id\n from\n to\n type\n properties\n workspaceId\n organizationId\n createdAt\n }\n }\n `;\n\n const variables = {\n input: {\n from: options.from,\n to: options.to,\n type: options.type,\n properties: options.properties,\n workspaceId: options.workspaceId || this.context.workspaceId,\n organizationId: options.organizationId,\n },\n };\n\n const response = await this.client.query<{ createGraphEdge: GraphEdge }>(mutation, variables, this.context);\n\n logger.info('[Graph] Edge created', { edgeId: response.createGraphEdge.id });\n\n return response.createGraphEdge;\n }\n\n /**\n * Get node by ID\n */\n public async getNode(nodeId: string): Promise<GraphNode | null> {\n logger.debug('[Graph] Getting node', { nodeId });\n\n const query = `\n query GetGraphNode($nodeId: ID!) {\n getGraphNode(nodeId: $nodeId) {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.query<{ getGraphNode: GraphNode | null }>(query, { nodeId }, this.context);\n\n return response.getGraphNode;\n }\n\n /**\n * Update node\n */\n public async updateNode(nodeId: string, properties: Record<string, unknown>): Promise<GraphNode> {\n logger.debug('[Graph] Updating node', { nodeId });\n\n const mutation = `\n mutation UpdateGraphNode($nodeId: ID!, $properties: JSON!) {\n updateGraphNode(nodeId: $nodeId, properties: $properties) {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.query<{ updateGraphNode: GraphNode }>(\n mutation,\n { nodeId, properties },\n this.context\n );\n\n logger.info('[Graph] Node updated', { nodeId });\n\n return response.updateGraphNode;\n }\n\n /**\n * Delete node\n */\n public async deleteNode(nodeId: string): Promise<boolean> {\n logger.debug('[Graph] Deleting node', { nodeId });\n\n const mutation = `\n mutation DeleteGraphNode($nodeId: ID!) {\n deleteGraphNode(nodeId: $nodeId) {\n success\n }\n }\n `;\n\n await this.client.query(mutation, { nodeId }, this.context);\n\n logger.info('[Graph] Node deleted', { nodeId });\n\n return true;\n }\n\n /**\n * Delete edge\n */\n public async deleteEdge(edgeId: string): Promise<boolean> {\n logger.debug('[Graph] Deleting edge', { edgeId });\n\n const mutation = `\n mutation DeleteGraphEdge($edgeId: ID!) {\n deleteGraphEdge(edgeId: $edgeId) {\n success\n }\n }\n `;\n\n await this.client.query(mutation, { edgeId }, this.context);\n\n logger.info('[Graph] Edge deleted', { edgeId });\n\n return true;\n }\n\n /**\n * Traverse graph\n */\n public async traverse(options: TraverseOptions): Promise<TraverseResult> {\n if (!options.startNode) {\n throw new ValidationError('Start node ID is required');\n }\n\n logger.debug('[Graph] Traversing graph', {\n startNode: options.startNode,\n direction: options.direction || 'outbound',\n });\n\n const query = `\n query TraverseGraph(\n $startNode: ID!\n $direction: GraphDirection\n $edgeTypes: [String!]\n $minDepth: Int\n $maxDepth: Int\n $limit: Int\n ) {\n traverseGraph(\n startNode: $startNode\n direction: $direction\n edgeTypes: $edgeTypes\n minDepth: $minDepth\n maxDepth: $maxDepth\n limit: $limit\n ) {\n nodes {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n edges {\n id\n from\n to\n type\n properties\n workspaceId\n organizationId\n createdAt\n }\n paths {\n nodes {\n id\n type\n properties\n }\n edges {\n id\n from\n to\n type\n }\n }\n }\n }\n `;\n\n const variables = {\n startNode: options.startNode,\n direction: options.direction || 'outbound',\n edgeTypes: options.edgeTypes,\n minDepth: options.minDepth || 1,\n maxDepth: options.maxDepth || 3,\n limit: options.limit || 100,\n };\n\n const response = await this.client.query<{ traverseGraph: TraverseResult }>(query, variables, this.context);\n\n return response.traverseGraph;\n }\n\n /**\n * Find shortest path between two nodes\n */\n public async findShortestPath(\n fromNode: string,\n toNode: string,\n options?: {\n edgeTypes?: string[];\n maxDepth?: number;\n }\n ): Promise<{\n nodes: GraphNode[];\n edges: GraphEdge[];\n distance: number;\n } | null> {\n logger.debug('[Graph] Finding shortest path', { fromNode, toNode });\n\n const query = `\n query FindShortestPath(\n $fromNode: ID!\n $toNode: ID!\n $edgeTypes: [String!]\n $maxDepth: Int\n ) {\n findShortestPath(\n fromNode: $fromNode\n toNode: $toNode\n edgeTypes: $edgeTypes\n maxDepth: $maxDepth\n ) {\n nodes {\n id\n type\n properties\n }\n edges {\n id\n from\n to\n type\n }\n distance\n }\n }\n `;\n\n const response = await this.client.query<{\n findShortestPath: {\n nodes: GraphNode[];\n edges: GraphEdge[];\n distance: number;\n } | null;\n }>(\n query,\n {\n fromNode,\n toNode,\n edgeTypes: options?.edgeTypes,\n maxDepth: options?.maxDepth || 10,\n },\n this.context\n );\n\n return response.findShortestPath;\n }\n\n /**\n * Query graph with raw openCypher. Proxied to wspace-graph-svc's\n * `executeCypher` resolver via the federated GraphQL gateway — no direct\n * graph-DB access. (Pre-2026-05 this used `executeNGQL` against NebulaGraph;\n * the federated resolver was renamed during the Apache AGE migration.)\n */\n public async query<T = unknown>(options: QueryGraphOptions): Promise<T[]> {\n if (!options.query) {\n throw new ValidationError('Cypher query is required');\n }\n\n logger.debug('[Graph] Executing Cypher query');\n\n const query = `\n query ExecuteCypher($query: String!, $bindVars: JSON, $limit: Int) {\n executeCypher(query: $query, bindVars: $bindVars, limit: $limit) {\n results\n }\n }\n `;\n\n const variables = {\n query: options.query,\n bindVars: options.bindVars,\n limit: options.limit || 1000,\n };\n\n const response = await this.client.query<{ executeCypher: { results: T[] } }>(query, variables, this.context);\n\n return response.executeCypher.results;\n }\n\n /**\n * Get neighbors of a node\n */\n public async getNeighbors(\n nodeId: string,\n options?: {\n direction?: 'outbound' | 'inbound' | 'any';\n edgeTypes?: string[];\n limit?: number;\n }\n ): Promise<{\n nodes: GraphNode[];\n edges: GraphEdge[];\n }> {\n logger.debug('[Graph] Getting neighbors', { nodeId });\n\n const query = `\n query GetNeighbors(\n $nodeId: ID!\n $direction: GraphDirection\n $edgeTypes: [String!]\n $limit: Int\n ) {\n getNeighbors(\n nodeId: $nodeId\n direction: $direction\n edgeTypes: $edgeTypes\n limit: $limit\n ) {\n nodes {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n edges {\n id\n from\n to\n type\n properties\n workspaceId\n organizationId\n createdAt\n }\n }\n }\n `;\n\n const response = await this.client.query<{\n getNeighbors: {\n nodes: GraphNode[];\n edges: GraphEdge[];\n };\n }>(\n query,\n {\n nodeId,\n direction: options?.direction || 'outbound',\n edgeTypes: options?.edgeTypes,\n limit: options?.limit || 100,\n },\n this.context\n );\n\n return response.getNeighbors;\n }\n\n /**\n * Get node degree (number of connections)\n */\n public async getNodeDegree(\n nodeId: string,\n direction?: 'outbound' | 'inbound' | 'any'\n ): Promise<{\n inbound: number;\n outbound: number;\n total: number;\n }> {\n logger.debug('[Graph] Getting node degree', { nodeId });\n\n const query = `\n query GetNodeDegree($nodeId: ID!, $direction: GraphDirection) {\n getNodeDegree(nodeId: $nodeId, direction: $direction) {\n inbound\n outbound\n total\n }\n }\n `;\n\n const response = await this.client.query<{\n getNodeDegree: {\n inbound: number;\n outbound: number;\n total: number;\n };\n }>(query, { nodeId, direction }, this.context);\n\n return response.getNodeDegree;\n }\n\n /**\n * Find nodes by properties\n */\n public async findNodes(\n type: string,\n filters: Record<string, unknown>,\n options?: {\n limit?: number;\n offset?: number;\n }\n ): Promise<{\n nodes: GraphNode[];\n total: number;\n }> {\n logger.debug('[Graph] Finding nodes', { type, filters });\n\n const query = `\n query FindGraphNodes(\n $type: String!\n $filters: JSON!\n $limit: Int\n $offset: Int\n ) {\n findGraphNodes(\n type: $type\n filters: $filters\n limit: $limit\n offset: $offset\n ) {\n nodes {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n total\n }\n }\n `;\n\n const response = await this.client.query<{\n findGraphNodes: {\n nodes: GraphNode[];\n total: number;\n };\n }>(\n query,\n {\n type,\n filters,\n limit: options?.limit || 100,\n offset: options?.offset || 0,\n },\n this.context\n );\n\n return response.findGraphNodes;\n }\n\n /**\n * Batch create nodes\n */\n public async createNodesBatch(nodes: CreateNodeOptions[]): Promise<GraphNode[]> {\n logger.debug('[Graph] Batch creating nodes', { count: nodes.length });\n\n const mutation = `\n mutation CreateGraphNodesBatch($nodes: [CreateGraphNodeInput!]!) {\n createGraphNodesBatch(nodes: $nodes) {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.query<{ createGraphNodesBatch: GraphNode[] }>(mutation, { nodes }, this.context);\n\n logger.info('[Graph] Nodes batch created', { count: response.createGraphNodesBatch.length });\n\n return response.createGraphNodesBatch;\n }\n\n /**\n * Batch create edges\n */\n public async createEdgesBatch(edges: CreateEdgeOptions[]): Promise<GraphEdge[]> {\n logger.debug('[Graph] Batch creating edges', { count: edges.length });\n\n const mutation = `\n mutation CreateGraphEdgesBatch($edges: [CreateGraphEdgeInput!]!) {\n createGraphEdgesBatch(edges: $edges) {\n id\n from\n to\n type\n properties\n workspaceId\n organizationId\n createdAt\n }\n }\n `;\n\n const response = await this.client.query<{ createGraphEdgesBatch: GraphEdge[] }>(mutation, { edges }, this.context);\n\n logger.info('[Graph] Edges batch created', { count: response.createGraphEdgesBatch.length });\n\n return response.createGraphEdgesBatch;\n }\n}\n\n/**\n * Export graph services, utilities, and middleware\n */\n// Export types\nexport type {\n GraphEventType,\n GraphEvent,\n EntityVertex,\n EdgeDocument,\n EntityGraphConfig,\n RelationshipGraphConfig,\n ModuleGraphConfig,\n SearchFilters,\n SearchResult,\n ProductFacet,\n TypeFacet,\n SearchFacets,\n SearchResponse,\n} from './types.js';\n\n// NOTE: GraphSyncService / GraphQueryService / GlobalSearchService were removed\n// during the AGE migration. Consuming services should use `defineModuleGraph`\n// to publish NATS events and use the SDK gateway client for reads.\n\n// Export utilities\nexport { GraphRegistry, createPrismaGraphIntegration } from './utils/index.js';\nexport type { PrismaGraphIntegration, PrismaGraphIntegrationOptions } from './utils/index.js';\nexport {\n createEntityEvent,\n createRelationshipEvent,\n extractMinimalFields,\n parseRelationship,\n getCollectionForEntity,\n extractEntityTitle,\n shouldSyncEntity,\n shouldSyncRelationship,\n} from './utils/helpers.js';\n\n// Export middleware\nexport { addGraphExtension } from './middleware/index.js';\nexport type { EntityEventType, GraphEventEmitter, GraphMiddlewareConfig } from './middleware/index.js';\n\n// Export Graph Events Helper\nexport { GraphEventsPublisher, getGraphEventsPublisher, createGraphEventsHelper } from './events-helper.js';\nexport type {\n GraphEventPublishOptions,\n GraphRelationshipData,\n GraphEntityConfig,\n GraphEventsHelperConfig,\n EntityEventData,\n GraphEventsHelper,\n} from './events-helper.js';\n\n// Export Graph Export Service\nexport { GraphExportService, createGraphExportService, createRelationshipFromEntity } from './export-service.js';\nexport type {\n GraphEntityExport,\n GraphRelationshipExport,\n GraphExportResponse,\n EntityFetcher,\n RelationshipFetcher,\n GraphExportServiceConfig,\n} from './export-service.js';\n\n// Export Unified Module Graph (recommended approach)\nexport { defineModuleGraph } from './module-graph.js';\nexport type {\n ModuleGraph,\n ModuleGraphDefinition,\n EntityDefinition,\n RelationshipDefinition,\n EntityEventContext,\n EntityEventHook,\n GraphEventOptions,\n RelationshipEventData,\n RelationshipExportData,\n GraphSchema,\n EntityRbacConfig,\n} from './module-graph.js';\n\n// Export New Generic Graph Configuration System (RECOMMENDED)\nexport {\n defineGraphConfig,\n defineEntity,\n defineRelationship,\n STANDARD_FIELDS,\n SOFT_DELETE_FIELDS,\n AUDIT_FIELDS,\n TENANT_FIELDS,\n} from './config/builder.js';\nexport type {\n GenericGraphConfig,\n GenericEntityConfig,\n GenericRelationshipConfig,\n DefineGraphConfigOptions,\n DefineEntityConfigOptions,\n DefineRelationshipConfigOptions,\n GraphValidationResult,\n GraphValidationError,\n} from './config/builder.js';\n\n// Export Graph Initialization\nexport { initializeGraph, isGraphInitialized, getGraphStats } from './config/init.js';\nexport type { InitializeGraphOptions } from './config/init.js';\n\n// Export all config types\nexport type {\n FieldMapper,\n ValidationErrorType,\n ExtractedEntityData,\n ExtractedRelationshipData,\n EntityRbacConfig as GenericEntityRbacConfig,\n} from './config/types.js';\n","/**\n * Reusable Prisma Client Graph Integration Utilities\n *\n * Provides standardized patterns for integrating Prisma with the Graph module,\n * supporting both standard Prisma and Prisma 7 adapter patterns.\n *\n * @module @burdenoff/be-sdk/graph/utils/prisma-helpers\n */\n\nimport type { PrismaClientBase } from '../../prisma/client.js';\nimport { ensureServiceApplicationName } from '../../prisma/client.js';\nimport type { GenericGraphConfig } from '../config/types.js';\nimport { initializeGraph } from '../index.js';\nimport { GraphEventEmitterImpl } from '../../event-queue/index.js';\nimport { logger } from '../../logger/index.js';\n\n/**\n * Configuration options for Prisma graph integration\n */\nexport interface PrismaGraphIntegrationOptions<TPrismaClient = unknown> {\n /**\n * Name of the service (for logging)\n * @example 'Tags Service', 'VibeControls Service'\n */\n serviceName: string;\n\n /**\n * Graph configuration from defineGraphConfig()\n */\n graphConfig: GenericGraphConfig;\n\n /**\n * Product name for event metadata\n * @default 'workspaces'\n */\n productName?: string;\n\n /**\n * Whether to validate configuration at runtime\n * @default true in development, false in production\n */\n validateRuntime?: boolean;\n\n /**\n * Whether to automatically initialize graph emitter on first database access\n * When true, initialization happens lazily when prisma or db() is first used\n * When false, you must manually call initializeGraphEmitter()\n * @default true\n */\n autoInit?: boolean;\n\n /**\n * Factory function to create base Prisma client\n * Supports both standard and adapter patterns\n *\n * @example\n * // Standard Prisma\n * createPrismaClient: () => new PrismaClient()\n *\n * @example\n * // Prisma 7 with adapter\n * createPrismaClient: () => {\n * const pool = new Pool({ connectionString: process.env.DATABASE_URL });\n * const adapter = new PrismaPg(pool);\n * return new PrismaClient({ adapter });\n * }\n */\n createPrismaClient: () => TPrismaClient;\n}\n\n/**\n * Singleton state for graph integration\n */\ninterface GraphIntegrationState<TPrismaClient> {\n graphEmitter: GraphEventEmitterImpl | null;\n extendedPrismaClient: TPrismaClient | null;\n emitterInitialized: boolean;\n initializationPromise: Promise<void> | null;\n}\n\n/**\n * Create a reusable Prisma graph integration manager\n *\n * This factory function creates a complete set of utilities for integrating\n * Prisma with the Graph module, handling initialization, client access, and cleanup.\n *\n * @template TPrismaClient The Prisma client type (supports generic for type safety)\n * @param options Configuration options\n * @returns Object with initialization functions and client accessors\n *\n * @example\n * ```typescript\n * // Standard Prisma with auto-initialization (default)\n * import { PrismaClient as PrismaClientClass } from '@prisma/client';\n * import { createPrismaGraphIntegration } from '@burdenoff/be-sdk/graph/utils/prisma-helpers';\n * import { graphConfig } from './graph.config.js';\n *\n * const {\n * prisma\n * } = createPrismaGraphIntegration({\n * serviceName: 'Tags Service',\n * graphConfig,\n * createPrismaClient: () => new PrismaClientClass(),\n * // autoInit: true is default - initialization happens automatically\n * });\n *\n * // Just use it! Initialization happens automatically on first access\n * const tags = await prisma.universalTag.findMany();\n *\n * // If you need manual control over initialization timing:\n * const {\n * initializeGraphEmitter,\n * prisma\n * } = createPrismaGraphIntegration({\n * serviceName: 'Tags Service',\n * graphConfig,\n * createPrismaClient: () => new PrismaClientClass(),\n * autoInit: false, // Disable auto-initialization\n * });\n *\n * // In your server startup (with autoInit: false):\n * await initializeGraphEmitter();\n * ```\n *\n * @example\n * ```typescript\n * // Prisma 7 with Adapter (VibeControls Service)\n * import { Pool } from 'pg';\n * import { PrismaClient as PrismaClientClass } from '@prisma/client';\n * import { PrismaPg } from '@prisma/adapter-pg';\n * import { createPrismaGraphIntegration } from '@burdenoff/be-sdk/graph/utils/prisma-helpers';\n * import { graphConfig } from './graph.config.js';\n *\n * const {\n * initializeGraphEmitter,\n * db,\n * prisma\n * } = createPrismaGraphIntegration({\n * serviceName: 'VibeControls Service',\n * graphConfig,\n * createPrismaClient: () => {\n * const pool = new Pool({ connectionString: process.env.DATABASE_URL });\n * const adapter = new PrismaPg(pool);\n * return new PrismaClientClass({ adapter });\n * },\n * });\n * ```\n */\nexport function createPrismaGraphIntegration<TPrismaClient extends PrismaClientBase>(\n options: PrismaGraphIntegrationOptions<TPrismaClient>\n): {\n initializeGraphEmitter: () => Promise<void>;\n db: () => { client: TPrismaClient };\n prisma: TPrismaClient;\n cleanup: () => Promise<void>;\n getGraphEmitter: () => GraphEventEmitterImpl | null;\n isInitialized: () => boolean;\n} {\n const {\n serviceName,\n graphConfig,\n productName = 'workspaces',\n validateRuntime = process.env.NODE_ENV !== 'production',\n autoInit = true,\n createPrismaClient,\n } = options;\n\n // Set per-service Postgres application_name (PGAPPNAME) up-front, BEFORE the\n // caller's `createPrismaClient` closure constructs its own pg Pool. That pool\n // bypasses be-sdk's createConnectionPool, so this env fallback is what makes\n // graph-integration services attributable in pg_stat_activity /\n // pg_stat_statements. Pure diagnostic metadata; only set when unset.\n ensureServiceApplicationName(productName);\n\n // Singleton state\n const state: GraphIntegrationState<TPrismaClient> = {\n graphEmitter: null,\n extendedPrismaClient: null,\n emitterInitialized: false,\n initializationPromise: null,\n };\n\n /**\n * Initialize the graph event emitter\n * Call this once during application startup before using the database\n *\n * If called multiple times, returns the same initialization promise\n *\n * @returns Promise that resolves when initialization is complete\n */\n async function initializeGraphEmitter(): Promise<void> {\n // Return existing promise if initialization is in progress or complete\n if (state.initializationPromise) {\n return state.initializationPromise;\n }\n\n // If already initialized (and promise was cleared), return immediately\n if (state.emitterInitialized) {\n return;\n }\n\n // Create and cache the initialization promise\n state.initializationPromise = (async () => {\n if (!process.env['GRAPH_EVENTS_ENABLED'] || process.env['GRAPH_EVENTS_ENABLED'] !== 'true') {\n logger.info(`[${serviceName}] Graph events disabled`);\n state.emitterInitialized = true;\n return;\n }\n\n try {\n // Ensure NATS_SERVERS is set (fallback to NATS_URL)\n if (!process.env['NATS_SERVERS'] && process.env['NATS_URL']) {\n process.env['NATS_SERVERS'] = process.env['NATS_URL'];\n }\n\n state.graphEmitter = new GraphEventEmitterImpl();\n // Note: GraphEventEmitterImpl auto-connects on first publishEntityEvent() call\n logger.info(`[${serviceName}] Graph event emitter initialized`);\n state.emitterInitialized = true;\n\n // Initialize graph integration with the configuration\n const basePrisma = createPrismaClient();\n\n state.extendedPrismaClient = initializeGraph(basePrisma, graphConfig, {\n productName,\n eventEmitter: state.graphEmitter,\n enabled: true,\n validateRuntime,\n });\n\n logger.info(`[${serviceName}] Graph integration initialized successfully`);\n } catch (error) {\n logger.error(`[${serviceName}] Failed to initialize graph integration:`, error);\n state.graphEmitter = null;\n state.extendedPrismaClient = null;\n state.emitterInitialized = true; // Mark as initialized to prevent retry loops\n }\n })();\n\n return state.initializationPromise;\n }\n\n /**\n * Get the Prisma client with graph integration\n *\n * Returns the extended Prisma client if graph events are enabled,\n * otherwise returns a fresh base client.\n *\n * When autoInit is enabled, triggers initialization on first call\n *\n * @returns Object with the Prisma client\n */\n function db(): { client: TPrismaClient } {\n // Auto-initialize if enabled and not yet initialized\n if (autoInit && !state.emitterInitialized && !state.initializationPromise) {\n logger.warn(\n `[${serviceName}] Graph emitter not initialized before first database access. Auto-initializing now. ` +\n `Consider calling 'await initializeGraphEmitter()' explicitly during server startup for better control.`\n );\n // Start initialization in the background (non-blocking)\n void initializeGraphEmitter();\n }\n\n // If graph events are not enabled or not initialized, create a base client\n if (\n !process.env['GRAPH_EVENTS_ENABLED'] ||\n process.env['GRAPH_EVENTS_ENABLED'] !== 'true' ||\n !state.extendedPrismaClient\n ) {\n const baseClient = createPrismaClient();\n return { client: baseClient };\n }\n\n return { client: state.extendedPrismaClient };\n }\n\n /**\n * Direct Prisma client accessor via Proxy\n *\n * A Proxy-based accessor that provides direct access to Prisma models\n * without needing to call a function.\n *\n * @example\n * ```typescript\n * const tags = await prisma.universalTag.findMany();\n * await prisma.$transaction([...]);\n * await prisma.$queryRaw`SELECT * FROM \"UniversalTag\"`;\n * ```\n */\n const prisma: TPrismaClient = new Proxy({} as TPrismaClient, {\n get(_, prop: string | symbol) {\n const { client } = db();\n const value = client[prop as keyof TPrismaClient];\n // If it's a function, bind it to the client\n if (typeof value === 'function') {\n return (value as (...args: unknown[]) => unknown).bind(client);\n }\n return value;\n },\n });\n\n /**\n * Cleanup function to disconnect clients and close emitters\n * Call this during application shutdown\n */\n async function cleanup(): Promise<void> {\n if (state.graphEmitter) {\n await state.graphEmitter.disconnect();\n logger.info(`[${serviceName}] Graph event emitter disconnected`);\n }\n\n if (state.extendedPrismaClient) {\n await state.extendedPrismaClient.$disconnect();\n state.extendedPrismaClient = null;\n logger.info(`[${serviceName}] Prisma client disconnected`);\n }\n\n state.emitterInitialized = false;\n }\n\n return {\n /**\n * Initialize graph event emitter\n *\n * With autoInit=true (default), this is called automatically on first database access.\n * You can still call it manually for explicit initialization timing.\n *\n * With autoInit=false, you must call this during application startup.\n */\n initializeGraphEmitter,\n\n /**\n * Get Prisma client with graph integration\n * Returns { client: PrismaClient }\n *\n * If autoInit is enabled, triggers initialization on first call.\n */\n db,\n\n /**\n * Direct Prisma client accessor (Proxy-based)\n * Use this for most database operations\n *\n * If autoInit is enabled, initialization happens automatically.\n */\n prisma,\n\n /**\n * Cleanup function for graceful shutdown\n */\n cleanup,\n\n /**\n * Get the raw graph emitter instance (for advanced use cases)\n */\n getGraphEmitter: () => state.graphEmitter,\n\n /**\n * Check if emitter is initialized\n */\n isInitialized: () => state.emitterInitialized,\n };\n}\n\n/**\n * Helper type to extract the return type of createPrismaGraphIntegration\n * Useful for type definitions in consuming services\n */\nexport type PrismaGraphIntegration<TPrismaClient extends PrismaClientBase> = ReturnType<\n typeof createPrismaGraphIntegration<TPrismaClient>\n>;\n","/**\n * Graph Events Helper\n *\n * Provides a configurable helper for publishing graph entity and relationship events.\n * This allows modules to define their entity types and automatically get event publishing\n * for graph synchronization.\n *\n * @module graph/events-helper\n * @category Graph\n *\n * @example\n * ```typescript\n * import { createGraphEventsHelper } from '@burdenoff/be-sdk/graph';\n *\n * // Create a helper for the tags module\n * const graphEvents = createGraphEventsHelper({\n * moduleName: 'module-tags',\n * entities: {\n * vocabulary: {\n * type: 'UniversalTagVocabulary',\n * getOrgId: (data) => data.tenantId as string,\n * getWorkspaceId: (data) => data.workspaceId as string,\n * },\n * tag: {\n * type: 'UniversalTag',\n * getOrgId: (data) => data.tenantId as string,\n * getWorkspaceId: (data) => data.workspaceId as string,\n * onCreated: async (data, publisher) => {\n * // Publish parent relationship if exists\n * if (data.parentId) {\n * await publisher.publishRelationshipCreated({ ... });\n * }\n * },\n * },\n * },\n * });\n *\n * // Use the helper\n * await graphEvents.vocabulary.created(vocabularyData);\n * await graphEvents.tag.updated(tagData);\n * ```\n */\nimport { logger } from '../logger/index.js';\nimport { getGraphEventEmitter, type EntityEventType, type GraphEventEmitter } from '../event-queue/graph-emitter.js';\n\n/**\n * Options for publishing events\n */\nexport interface GraphEventPublishOptions {\n userId?: string;\n correlationId?: string;\n}\n\n/**\n * Relationship data for graph sync\n */\nexport interface GraphRelationshipData {\n from: { id: string; type: string };\n to: { id: string; type: string };\n relationType: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Entity configuration for graph events\n */\nexport interface GraphEntityConfig {\n /** GraphQL/Database entity type name (e.g., 'UniversalTag') */\n type: string;\n /** Extract organization/tenant ID from entity data */\n getOrgId?: (data: Record<string, unknown>) => string | undefined;\n /** Extract workspace ID from entity data */\n getWorkspaceId?: (data: Record<string, unknown>) => string | undefined;\n /** Hook called after entity created event is published */\n onCreated?: (\n data: Record<string, unknown>,\n publisher: GraphEventsPublisher,\n options?: GraphEventPublishOptions\n ) => Promise<void>;\n /** Hook called after entity updated event is published */\n onUpdated?: (\n data: Record<string, unknown>,\n publisher: GraphEventsPublisher,\n options?: GraphEventPublishOptions\n ) => Promise<void>;\n /** Hook called after entity deleted event is published */\n onDeleted?: (\n data: Record<string, unknown>,\n publisher: GraphEventsPublisher,\n options?: GraphEventPublishOptions\n ) => Promise<void>;\n}\n\n/**\n * Configuration for graph events helper\n */\nexport interface GraphEventsHelperConfig {\n /** Module/product name for event context */\n moduleName: string;\n /** Entity configurations keyed by friendly name */\n entities: Record<string, GraphEntityConfig>;\n}\n\n/**\n * Entity event data for graph sync\n */\nexport interface EntityEventData {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n}\n\n/**\n * Graph Events Publisher\n *\n * Singleton service for publishing entity and relationship events\n * to the graph synchronization system.\n */\nexport class GraphEventsPublisher {\n private static instance: GraphEventsPublisher | null = null;\n private productName: string;\n private initialized = false;\n private emitter: GraphEventEmitter | null = null;\n\n constructor(productName: string = 'unknown') {\n this.productName = productName;\n }\n\n /**\n * Get singleton instance\n */\n static getInstance(productName?: string): GraphEventsPublisher {\n if (!GraphEventsPublisher.instance) {\n GraphEventsPublisher.instance = new GraphEventsPublisher(productName);\n }\n return GraphEventsPublisher.instance;\n }\n\n /**\n * Set the product name (useful when using singleton)\n */\n setProductName(name: string): void {\n this.productName = name;\n }\n\n /**\n * Initialize the publisher\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n try {\n this.emitter = getGraphEventEmitter();\n logger.info('[GraphEventsPublisher] Graph event emitter initialized');\n this.initialized = true;\n\n const natsUrl = process.env['NATS_URL'] || process.env['NATS_SERVERS'];\n if (natsUrl) {\n logger.info(`[GraphEventsPublisher] NATS configured: ${natsUrl}`);\n } else {\n logger.warn('[GraphEventsPublisher] NATS not configured, using in-memory fallback');\n }\n } catch (error) {\n logger.error('[GraphEventsPublisher] Failed to initialize:', error);\n }\n }\n\n /**\n * Ensure initialized before publishing\n */\n private async ensureInitialized(): Promise<void> {\n if (!this.initialized) {\n await this.initialize();\n }\n }\n\n /**\n * Publish entity created event\n */\n async publishEntityCreated(entity: EntityEventData, options?: GraphEventPublishOptions): Promise<void> {\n await this.publishEntityEvent('entity.created', entity, options);\n }\n\n /**\n * Publish entity updated event\n */\n async publishEntityUpdated(entity: EntityEventData, options?: GraphEventPublishOptions): Promise<void> {\n await this.publishEntityEvent('entity.updated', entity, options);\n }\n\n /**\n * Publish entity deleted event\n */\n async publishEntityDeleted(entity: EntityEventData, options?: GraphEventPublishOptions): Promise<void> {\n await this.publishEntityEvent('entity.deleted', entity, options);\n }\n\n /**\n * Publish relationship created event\n */\n async publishRelationshipCreated(\n relationship: GraphRelationshipData,\n organizationId: string,\n options?: GraphEventPublishOptions\n ): Promise<void> {\n await this.publishRelationshipEvent('relationship.created', relationship, organizationId, options);\n }\n\n /**\n * Publish relationship deleted event\n */\n async publishRelationshipDeleted(\n relationship: GraphRelationshipData,\n organizationId: string,\n options?: GraphEventPublishOptions\n ): Promise<void> {\n await this.publishRelationshipEvent('relationship.deleted', relationship, organizationId, options);\n }\n\n /**\n * Internal method to publish entity events\n */\n private async publishEntityEvent(\n eventType: EntityEventType,\n entity: EntityEventData,\n options?: GraphEventPublishOptions\n ): Promise<void> {\n await this.ensureInitialized();\n\n if (!this.emitter) {\n logger.warn('[GraphEventsPublisher] Emitter not initialized, skipping event');\n return;\n }\n\n try {\n await this.emitter.publishEntityEvent(\n eventType,\n {\n id: entity.id,\n type: entity.type,\n data: entity.data,\n },\n {\n productName: this.productName,\n organizationId: entity.organizationId || 'unknown',\n workspaceId: entity.workspaceId,\n actorId: options?.userId,\n }\n );\n\n logger.debug(`[GraphEventsPublisher] Published ${eventType} for ${entity.type}:${entity.id}`);\n } catch (error) {\n logger.error(`[GraphEventsPublisher] Failed to publish ${eventType} for ${entity.type}:${entity.id}:`, error);\n }\n }\n\n /**\n * Internal method to publish relationship events\n */\n private async publishRelationshipEvent(\n eventType: 'relationship.created' | 'relationship.deleted',\n relationship: GraphRelationshipData,\n organizationId: string,\n options?: GraphEventPublishOptions\n ): Promise<void> {\n await this.ensureInitialized();\n\n if (!this.emitter) {\n logger.warn('[GraphEventsPublisher] Emitter not initialized, skipping event');\n return;\n }\n\n try {\n await this.emitter.publishEntityEvent(\n eventType as EntityEventType,\n {\n id: `${relationship.from.id}_${relationship.to.id}`,\n type: relationship.relationType,\n data: {\n from: relationship.from,\n to: relationship.to,\n metadata: relationship.metadata,\n },\n },\n {\n productName: this.productName,\n organizationId,\n actorId: options?.userId,\n }\n );\n\n logger.debug(`[GraphEventsPublisher] Published ${eventType} for ${relationship.relationType}`);\n } catch (error) {\n logger.error(`[GraphEventsPublisher] Failed to publish ${eventType} for ${relationship.relationType}:`, error);\n }\n }\n\n /**\n * Shutdown the publisher\n */\n async shutdown(): Promise<void> {\n this.initialized = false;\n this.emitter = null;\n logger.info('[GraphEventsPublisher] Shutdown complete');\n }\n\n /**\n * Reset singleton (for testing)\n */\n static reset(): void {\n GraphEventsPublisher.instance = null;\n }\n}\n\n/**\n * Get singleton GraphEventsPublisher instance\n */\nexport function getGraphEventsPublisher(productName?: string): GraphEventsPublisher {\n return GraphEventsPublisher.getInstance(productName);\n}\n\n/**\n * Entity event handler type\n */\ntype EntityEventHandler = (data: Record<string, unknown>, options?: GraphEventPublishOptions) => Promise<void>;\n\n/**\n * Entity events object type\n */\ninterface EntityEvents {\n created: EntityEventHandler;\n updated: EntityEventHandler;\n deleted: EntityEventHandler;\n}\n\n/**\n * Graph events helper type\n */\nexport type GraphEventsHelper = Record<string, EntityEvents>;\n\n/**\n * Create a graph events helper with configured entity types\n */\nexport function createGraphEventsHelper(config: GraphEventsHelperConfig): GraphEventsHelper {\n const publisher = new GraphEventsPublisher(config.moduleName);\n const helper: GraphEventsHelper = {};\n\n for (const [name, entityConfig] of Object.entries(config.entities)) {\n helper[name] = {\n created: async (data: Record<string, unknown>, options?: GraphEventPublishOptions): Promise<void> => {\n await publisher.publishEntityCreated(\n {\n id: data['id'] as string,\n type: entityConfig.type,\n data,\n organizationId: entityConfig.getOrgId?.(data),\n workspaceId: entityConfig.getWorkspaceId?.(data),\n },\n options\n );\n\n // Call hook if defined\n if (entityConfig.onCreated) {\n await entityConfig.onCreated(data, publisher, options);\n }\n },\n updated: async (data: Record<string, unknown>, options?: GraphEventPublishOptions): Promise<void> => {\n await publisher.publishEntityUpdated(\n {\n id: data['id'] as string,\n type: entityConfig.type,\n data,\n organizationId: entityConfig.getOrgId?.(data),\n workspaceId: entityConfig.getWorkspaceId?.(data),\n },\n options\n );\n\n if (entityConfig.onUpdated) {\n await entityConfig.onUpdated(data, publisher, options);\n }\n },\n deleted: async (data: Record<string, unknown>, options?: GraphEventPublishOptions): Promise<void> => {\n await publisher.publishEntityDeleted(\n {\n id: data['id'] as string,\n type: entityConfig.type,\n data,\n organizationId: entityConfig.getOrgId?.(data),\n workspaceId: entityConfig.getWorkspaceId?.(data),\n },\n options\n );\n\n if (entityConfig.onDeleted) {\n await entityConfig.onDeleted(data, publisher, options);\n }\n },\n };\n }\n\n return helper;\n}\n","/**\n * Graph Export Service\n *\n * Provides a configurable service for exporting entities and relationships\n * to be consumed by the graph module for synchronization.\n *\n * @module graph/export-service\n * @category Graph\n *\n * @example\n * ```typescript\n * import { createGraphExportService } from '@burdenoff/be-sdk/graph';\n *\n * const exportService = createGraphExportService({\n * moduleName: 'module-tags',\n * config: tagsGraphConfig,\n * fetchers: {\n * UniversalTag: async (workspaceId) => db.universalTag.findMany({ where: { workspaceId } }),\n * UniversalTagVocabulary: async (workspaceId) => db.universalTagVocabulary.findMany({ where: { workspaceId } }),\n * },\n * relationshipFetchers: {\n * tagHierarchy: async (workspaceId) => fetchTagHierarchyRelationships(workspaceId),\n * },\n * });\n *\n * // Export all data\n * const result = await exportService.exportAll(organizationId, workspaceId);\n *\n * // Export only entities\n * const entities = await exportService.exportEntities(organizationId, workspaceId);\n * ```\n */\nimport { logger } from '../logger/index.js';\nimport type { ModuleGraphConfig, RelationshipGraphConfig } from './types.js';\n\n/**\n * Entity data structure for graph export\n */\nexport interface GraphEntityExport {\n /** Entity ID */\n id: string;\n /** Entity type */\n type: string;\n /** Entity data */\n data: Record<string, unknown>;\n /** Organization/Tenant ID */\n organizationId?: string;\n /** Workspace ID */\n workspaceId?: string;\n /** Creation timestamp */\n createdAt: string;\n /** Last update timestamp */\n updatedAt: string;\n}\n\n/**\n * Relationship data structure for graph export\n */\nexport interface GraphRelationshipExport {\n /** Relationship ID */\n id: string;\n /** Relationship type */\n type: string;\n /** Source entity ID */\n fromId: string;\n /** Source entity type */\n fromType: string;\n /** Target entity ID */\n toId: string;\n /** Target entity type */\n toType: string;\n /** Relationship metadata */\n metadata: Record<string, unknown>;\n /** Creation timestamp */\n createdAt: string;\n /** Last update timestamp */\n updatedAt: string;\n}\n\n/**\n * Complete graph export response\n */\nexport interface GraphExportResponse {\n /** Module name */\n moduleName: string;\n /** Product source identifier */\n productSource: string;\n /** Export timestamp */\n exportedAt: string;\n /** Schema information */\n schema: {\n entities: Record<string, { fields: string[]; collection: string }>;\n relationships: Record<\n string,\n {\n from: string;\n fromType: string;\n to: string;\n toType: string;\n edgeType: string;\n }\n >;\n };\n /** Exported data */\n data: {\n entities: Record<string, GraphEntityExport[]>;\n relationships: GraphRelationshipExport[];\n };\n /** Export statistics */\n stats: {\n totalEntities: number;\n totalRelationships: number;\n entityCounts: Record<string, number>;\n };\n}\n\n/**\n * Entity fetcher function type\n */\nexport type EntityFetcher<T = Record<string, unknown>> = (\n organizationId?: string,\n workspaceId?: string\n) => Promise<T[]>;\n\n/**\n * Relationship fetcher function type\n */\nexport type RelationshipFetcher = (organizationId?: string, workspaceId?: string) => Promise<GraphRelationshipExport[]>;\n\n/**\n * Configuration for graph export service\n */\nexport interface GraphExportServiceConfig {\n /** Module name */\n moduleName: string;\n /** Graph configuration */\n config: ModuleGraphConfig;\n /** Entity fetcher functions keyed by entity type */\n fetchers: Record<string, EntityFetcher>;\n /** Relationship fetcher functions */\n relationshipFetchers?: Record<string, RelationshipFetcher>;\n /** Custom entity transformer */\n transformEntity?: (type: string, item: Record<string, unknown>) => GraphEntityExport;\n}\n\n/**\n * Graph Export Service\n *\n * Handles exporting entity and relationship data for graph synchronization.\n */\nexport class GraphExportService {\n private readonly moduleName: string;\n private readonly config: ModuleGraphConfig;\n private readonly fetchers: Record<string, EntityFetcher>;\n private readonly relationshipFetchers: Record<string, RelationshipFetcher>;\n private readonly customTransformer?: (type: string, item: Record<string, unknown>) => GraphEntityExport;\n\n constructor(serviceConfig: GraphExportServiceConfig) {\n this.moduleName = serviceConfig.moduleName;\n this.config = serviceConfig.config;\n this.fetchers = serviceConfig.fetchers;\n this.relationshipFetchers = serviceConfig.relationshipFetchers || {};\n this.customTransformer = serviceConfig.transformEntity;\n }\n\n /**\n * Get the graph configuration schema\n */\n getSchema(): {\n moduleName: string;\n entities: Record<string, { fields: string[]; collection: string }>;\n relationships: Record<\n string,\n {\n from: string;\n fromType: string;\n to: string;\n toType: string;\n edgeType: string;\n }\n >;\n } {\n const entities: Record<string, { fields: string[]; collection: string }> = {};\n const relationships: Record<\n string,\n {\n from: string;\n fromType: string;\n to: string;\n toType: string;\n edgeType: string;\n }\n > = {};\n\n // Transform entity config\n for (const [entityType, config] of Object.entries(this.config.entities)) {\n entities[entityType] = {\n fields: Array.isArray(config.fields) ? config.fields : ['id', 'createdAt', 'updatedAt'],\n collection: config.collection || 'product_entities',\n };\n }\n\n // Transform relationship config\n if (this.config.relationships) {\n for (const [relType, config] of Object.entries(this.config.relationships)) {\n relationships[relType] = {\n from: config.from,\n fromType: config.from,\n to: config.to,\n toType: config.to,\n edgeType: config.label || 'relates_to',\n };\n }\n }\n\n return {\n moduleName: this.config.moduleName,\n entities,\n relationships,\n };\n }\n\n /**\n * Export all entities for a given organization/workspace\n */\n async exportEntities(\n organizationId?: string,\n workspaceId?: string,\n entityTypes?: string[]\n ): Promise<Record<string, GraphEntityExport[]>> {\n const result: Record<string, GraphEntityExport[]> = {};\n const typesToExport = entityTypes || Object.keys(this.config.entities);\n\n for (const entityType of typesToExport) {\n if (!this.config.entities[entityType]) {\n continue;\n }\n\n const fetcher = this.fetchers[entityType];\n if (!fetcher) {\n logger.warn(`[GraphExportService] No fetcher for ${entityType}`);\n result[entityType] = [];\n continue;\n }\n\n try {\n const entities = await fetcher(organizationId, workspaceId);\n result[entityType] = entities.map((item) => this.transformEntity(entityType, item));\n } catch (error) {\n logger.error(`[GraphExportService] Error fetching ${entityType}:`, error);\n result[entityType] = [];\n }\n }\n\n return result;\n }\n\n /**\n * Export all relationships for a given organization/workspace\n */\n async exportRelationships(organizationId?: string, workspaceId?: string): Promise<GraphRelationshipExport[]> {\n const relationships: GraphRelationshipExport[] = [];\n\n for (const [name, fetcher] of Object.entries(this.relationshipFetchers)) {\n try {\n const rels = await fetcher(organizationId, workspaceId);\n relationships.push(...rels);\n } catch (error) {\n logger.error(`[GraphExportService] Error fetching relationships ${name}:`, error);\n }\n }\n\n return relationships;\n }\n\n /**\n * Export complete graph data (schema + entities + relationships)\n */\n async exportAll(organizationId?: string, workspaceId?: string): Promise<GraphExportResponse> {\n const schema = this.getSchema();\n const entities = await this.exportEntities(organizationId, workspaceId);\n const relationships = await this.exportRelationships(organizationId, workspaceId);\n\n // Calculate stats\n const entityCounts: Record<string, number> = {};\n let totalEntities = 0;\n\n for (const [type, items] of Object.entries(entities)) {\n entityCounts[type] = items.length;\n totalEntities += items.length;\n }\n\n return {\n moduleName: this.config.moduleName,\n productSource: this.moduleName,\n exportedAt: new Date().toISOString(),\n schema: {\n entities: schema.entities,\n relationships: schema.relationships,\n },\n data: {\n entities,\n relationships,\n },\n stats: {\n totalEntities,\n totalRelationships: relationships.length,\n entityCounts,\n },\n };\n }\n\n /**\n * Transform a database entity to graph export format\n */\n private transformEntity(type: string, item: Record<string, unknown>): GraphEntityExport {\n if (this.customTransformer) {\n return this.customTransformer(type, item);\n }\n\n const { id, createdAt, updatedAt, workspaceId, tenantId, ...data } = item as {\n id: string;\n createdAt: Date | string;\n updatedAt: Date | string;\n workspaceId?: string;\n tenantId?: string;\n [key: string]: unknown;\n };\n\n return {\n id,\n type,\n data,\n organizationId: tenantId,\n workspaceId,\n createdAt: createdAt instanceof Date ? createdAt.toISOString() : String(createdAt),\n updatedAt: updatedAt instanceof Date ? updatedAt.toISOString() : String(updatedAt),\n };\n }\n}\n\n/**\n * Create a graph export service instance\n */\nexport function createGraphExportService(config: GraphExportServiceConfig): GraphExportService {\n return new GraphExportService(config);\n}\n\n/**\n * Helper function to create a relationship from entity data\n */\nexport function createRelationshipFromEntity(\n entity: Record<string, unknown>,\n relationConfig: RelationshipGraphConfig,\n relationType: string\n): GraphRelationshipExport | null {\n const fromId = entity[relationConfig.from] as string | undefined;\n const toId = entity[relationConfig.to] as string | undefined;\n\n if (!fromId || !toId) {\n return null;\n }\n\n const metadata = relationConfig.extractMetadata ? relationConfig.extractMetadata(entity) : {};\n\n return {\n id: `${relationType}_${entity['id'] || fromId}_${toId}`,\n type: relationType,\n fromId,\n fromType: relationConfig.from || 'Entity',\n toId,\n toType: relationConfig.to || 'Entity',\n metadata,\n createdAt:\n entity['createdAt'] instanceof Date\n ? entity['createdAt'].toISOString()\n : String(entity['createdAt'] || new Date().toISOString()),\n updatedAt:\n entity['updatedAt'] instanceof Date\n ? entity['updatedAt'].toISOString()\n : String(entity['updatedAt'] || new Date().toISOString()),\n };\n}\n","/**\n * Unified Module Graph Definition\n *\n * Provides a single, simplified configuration for graph integration in microservices.\n * Combines schema definition, event publishing, and data export into one unified API.\n *\n * @module graph/module-graph\n * @category Graph\n *\n * @example\n * ```typescript\n * // In your microservice: src/modules/[module]/graph.ts\n * import { defineModuleGraph } from '@burdenoff/be-sdk/graph';\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n *\n * export const tagsGraph = defineModuleGraph({\n * moduleName: 'module-tags',\n *\n * entities: {\n * vocabulary: {\n * type: 'UniversalTagVocabulary',\n * fields: ['id', 'name', 'description', 'workspaceId'],\n * getOrgId: (data) => data.tenantId,\n * getWorkspaceId: (data) => data.workspaceId,\n * fetch: async (_, workspaceId) =>\n * getDb().client.universalTagVocabulary.findMany({\n * where: { deletedAt: null, ...(workspaceId && { workspaceId }) },\n * }),\n * },\n *\n * tag: {\n * type: 'UniversalTag',\n * fields: ['id', 'name', 'vocabularyId', 'parentId'],\n * getOrgId: (data) => data.tenantId,\n * getWorkspaceId: (data) => data.workspaceId,\n * onCreated: async (data, ctx) => {\n * if (data.parentId) {\n * await ctx.publishRelationship({\n * from: { id: data.id, type: 'UniversalTag' },\n * to: { id: data.parentId, type: 'UniversalTag' },\n * relationType: 'child_of',\n * });\n * }\n * },\n * fetch: async (_, workspaceId) =>\n * getDb().client.universalTag.findMany({\n * where: { deletedAt: null, ...(workspaceId && { workspaceId }) },\n * }),\n * },\n * },\n *\n * relationships: {\n * tagHierarchy: {\n * fromType: 'UniversalTag',\n * toType: 'UniversalTag',\n * edgeType: 'child_of',\n * fetch: async (_, workspaceId) => {\n * const tags = await getDb().client.universalTag.findMany({\n * where: { deletedAt: null, parentId: { not: null }, ...(workspaceId && { workspaceId }) },\n * });\n * return tags.map(t => ({\n * id: `hierarchy_${t.id}`,\n * fromId: t.id,\n * toId: t.parentId!,\n * metadata: { hierarchyPath: t.hierarchyPath },\n * }));\n * },\n * },\n * },\n * });\n *\n * // Usage in providers:\n * await tagsGraph.events.vocabulary.created(data);\n * await tagsGraph.events.tag.updated(data);\n *\n * // Usage in index.ts:\n * await tagsGraph.initialize();\n * const schema = tagsGraph.getSchema();\n * const exportData = await tagsGraph.exportAll(orgId, workspaceId);\n * ```\n */\nimport { logger } from '../logger/index.js';\nimport {\n getGraphEventEmitter,\n type EntityEventType,\n type GraphEventEmitter,\n type EntityEventRbacMetadata,\n} from '../event-queue/graph-emitter.js';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\n/**\n * Options for publishing events\n */\nexport interface GraphEventOptions {\n actorId?: string;\n correlationId?: string;\n organizationId?: string;\n}\n\n/**\n * Relationship data for graph events\n */\nexport interface RelationshipEventData {\n from: { id: string; type: string };\n to: { id: string; type: string };\n relationType: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Context provided to entity event hooks\n */\nexport interface EntityEventContext {\n /** Publish a relationship event */\n publishRelationship: (data: RelationshipEventData, orgId?: string) => Promise<void>;\n /** Publish relationship deleted event */\n deleteRelationship: (data: RelationshipEventData, orgId?: string) => Promise<void>;\n /** Get the organization ID from entity data */\n getOrgId: (data: Record<string, unknown>) => string | undefined;\n /** Get the workspace ID from entity data */\n getWorkspaceId: (data: Record<string, unknown>) => string | undefined;\n}\n\n/**\n * Entity event hook function type\n */\nexport type EntityEventHook = (\n data: Record<string, unknown>,\n ctx: EntityEventContext,\n options?: GraphEventOptions\n) => Promise<void>;\n\n/**\n * Entity fetcher function for export\n */\nexport type EntityFetcher<T = Record<string, unknown>> = (\n organizationId?: string,\n workspaceId?: string\n) => Promise<T[]>;\n\n/**\n * Relationship export data\n */\nexport interface RelationshipExportData {\n id: string;\n fromId: string;\n toId: string;\n metadata?: Record<string, unknown>;\n createdAt?: string;\n updatedAt?: string;\n}\n\n/**\n * Relationship fetcher function for export\n */\nexport type RelationshipFetcher = (organizationId?: string, workspaceId?: string) => Promise<RelationshipExportData[]>;\n\n/**\n * RBAC configuration for an entity in the graph.\n * When provided, entity lifecycle events will include RBAC metadata,\n * enabling the RBAC consumer to automatically create/update/delete resources.\n */\nexport interface EntityRbacConfig {\n /** RBAC resource type name (e.g., 'tag', 'conversation', 'bot') */\n resourceTypeName: string;\n /** Extract human-readable name for the RBAC resource. Falls back to entity title. */\n extractName?: (data: Record<string, unknown>) => string | undefined;\n /** Extract a custom identifier for the RBAC resource. Defaults to entity id. */\n extractIdentifier?: (data: Record<string, unknown>) => string | undefined;\n /** Field name on the entity data whose value is used as parentResourceIdentifier in RBAC */\n parentResourceField?: string;\n /** Whether to create an RBAC resource for this entity (default: true) */\n createResource?: boolean;\n}\n\n/**\n * Entity definition in the unified graph config\n */\nexport interface EntityDefinition<T = Record<string, unknown>> {\n /** GraphQL/Database type name (e.g., 'UniversalTag') */\n type: string;\n\n /** Fields to include in graph schema */\n fields?: string[];\n\n /** graph entity label (defaults to 'entity') */\n collection?: string;\n\n /** Extract organization/tenant ID from entity data */\n getOrgId?: (data: Record<string, unknown>) => string | undefined;\n\n /** Extract workspace ID from entity data */\n getWorkspaceId?: (data: Record<string, unknown>) => string | undefined;\n\n /** Hook called after entity created */\n onCreated?: EntityEventHook;\n\n /** Hook called after entity updated */\n onUpdated?: EntityEventHook;\n\n /** Hook called after entity deleted */\n onDeleted?: EntityEventHook;\n\n /** Fetch entities for export (optional - needed only for export API) */\n fetch?: EntityFetcher<T>;\n\n /**\n * RBAC resource tracking configuration.\n * When provided, entity lifecycle events carry RBAC metadata so the\n * rbac-entity-consumer can automatically create/update/delete RBAC resources\n * in sync with the entity's lifecycle.\n */\n rbac?: EntityRbacConfig;\n}\n\n/**\n * Relationship definition in the unified graph config\n */\nexport interface RelationshipDefinition {\n /** Source entity type */\n fromType: string;\n\n /** Target entity type */\n toType: string;\n\n /** Edge type/collection name (e.g., 'child_of', 'tagged_with') */\n edgeType: string;\n\n /** Extract metadata from relationship record */\n extractMetadata?: (record: Record<string, unknown>) => Record<string, unknown>;\n\n /** Fetch relationships for export (optional - needed only for export API) */\n fetch?: RelationshipFetcher;\n}\n\n/**\n * Configuration for defineModuleGraph\n */\nexport interface ModuleGraphDefinition {\n /** Module name (e.g., 'module-tags') */\n moduleName: string;\n\n /**\n * Product source identifier stored in the graph DB and used for filtering.\n * Defaults to moduleName if not set.\n * Use this to group multiple modules under a single product identifier\n * (e.g., set productSource: 'vibecontrols' on all vibecontrols modules so\n * the frontend can filter with productSources: ['vibecontrols']).\n */\n productSource?: string;\n\n /** Entity definitions keyed by friendly name */\n entities: Record<string, EntityDefinition>;\n\n /** Relationship definitions keyed by name */\n relationships?: Record<string, RelationshipDefinition>;\n}\n\n/**\n * Entity event methods\n */\ninterface EntityEventMethods {\n created: (data: Record<string, unknown>, options?: GraphEventOptions) => Promise<void>;\n updated: (data: Record<string, unknown>, options?: GraphEventOptions) => Promise<void>;\n deleted: (data: Record<string, unknown>, options?: GraphEventOptions) => Promise<void>;\n}\n\n/**\n * Entity export data\n */\ninterface EntityExport {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Relationship export data (full)\n */\ninterface RelationshipExport {\n id: string;\n type: string;\n fromId: string;\n fromType: string;\n toId: string;\n toType: string;\n metadata: Record<string, unknown>;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Graph schema\n */\ninterface GraphSchema {\n moduleName: string;\n entities: Record<string, { fields: string[]; collection: string }>;\n relationships: Record<string, { fromType: string; toType: string; edgeType: string }>;\n}\n\n/**\n * Export response\n */\ninterface ExportResponse {\n moduleName: string;\n productSource: string;\n exportedAt: string;\n schema: GraphSchema;\n data: {\n entities: Record<string, EntityExport[]>;\n relationships: RelationshipExport[];\n };\n stats: {\n totalEntities: number;\n totalRelationships: number;\n entityCounts: Record<string, number>;\n };\n}\n\n/**\n * The unified module graph instance\n */\nexport interface ModuleGraph {\n /** Module name */\n readonly moduleName: string;\n\n /** Entity event helpers */\n readonly events: Record<string, EntityEventMethods>;\n\n /** Initialize the graph (call on startup) */\n initialize(): Promise<void>;\n\n /** Shutdown the graph (call on exit) */\n shutdown(): Promise<void>;\n\n /** Get the graph schema */\n getSchema(): GraphSchema;\n\n /** Export all entities */\n exportEntities(\n organizationId?: string,\n workspaceId?: string,\n entityTypes?: string[]\n ): Promise<Record<string, EntityExport[]>>;\n\n /** Export all relationships */\n exportRelationships(organizationId?: string, workspaceId?: string): Promise<RelationshipExport[]>;\n\n /** Export everything (schema + entities + relationships) */\n exportAll(organizationId?: string, workspaceId?: string): Promise<ExportResponse>;\n\n /** Get the raw graph events publisher (for advanced use) */\n getPublisher(): GraphEventsPublisherInternal;\n}\n\n// =============================================================================\n// INTERNAL PUBLISHER\n// =============================================================================\n\n/**\n * Internal graph events publisher\n */\nclass GraphEventsPublisherInternal {\n private productName: string;\n private initialized = false;\n private emitter: GraphEventEmitter | null = null;\n\n constructor(productName: string) {\n this.productName = productName;\n }\n\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n try {\n this.emitter = getGraphEventEmitter();\n logger.info(`[ModuleGraph:${this.productName}] Graph event emitter initialized`);\n this.initialized = true;\n\n const natsUrl = process.env['NATS_URL'] || process.env['NATS_SERVERS'];\n if (natsUrl) {\n logger.info(`[ModuleGraph:${this.productName}] NATS configured: ${natsUrl}`);\n } else {\n logger.warn(`[ModuleGraph:${this.productName}] NATS not configured, using in-memory fallback`);\n }\n } catch (error) {\n logger.error(`[ModuleGraph:${this.productName}] Failed to initialize:`, error);\n }\n }\n\n private async ensureInitialized(): Promise<void> {\n if (!this.initialized) {\n await this.initialize();\n }\n }\n\n async publishEntityCreated(\n entity: {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n },\n options?: GraphEventOptions,\n rbac?: EntityEventRbacMetadata\n ): Promise<void> {\n await this.publishEntityEvent('entity.created', entity, options, rbac);\n }\n\n async publishEntityUpdated(\n entity: {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n },\n options?: GraphEventOptions,\n rbac?: EntityEventRbacMetadata\n ): Promise<void> {\n await this.publishEntityEvent('entity.updated', entity, options, rbac);\n }\n\n async publishEntityDeleted(\n entity: {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n },\n options?: GraphEventOptions,\n rbac?: EntityEventRbacMetadata\n ): Promise<void> {\n await this.publishEntityEvent('entity.deleted', entity, options, rbac);\n }\n\n async publishRelationshipCreated(\n relationship: RelationshipEventData,\n organizationId: string,\n options?: GraphEventOptions\n ): Promise<void> {\n await this.publishRelationshipEvent('relationship.created', relationship, organizationId, options);\n }\n\n async publishRelationshipDeleted(\n relationship: RelationshipEventData,\n organizationId: string,\n options?: GraphEventOptions\n ): Promise<void> {\n await this.publishRelationshipEvent('relationship.deleted', relationship, organizationId, options);\n }\n\n private async publishEntityEvent(\n eventType: EntityEventType,\n entity: {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n },\n options?: GraphEventOptions,\n rbac?: EntityEventRbacMetadata\n ): Promise<void> {\n await this.ensureInitialized();\n\n if (!this.emitter) {\n logger.warn(`[ModuleGraph:${this.productName}] Emitter not initialized, skipping event`);\n return;\n }\n\n try {\n await this.emitter.publishEntityEvent(\n eventType,\n {\n id: entity.id,\n type: entity.type,\n data: entity.data,\n },\n {\n productName: this.productName,\n organizationId: options?.organizationId ?? entity.organizationId ?? 'unknown',\n workspaceId: entity.workspaceId,\n actorId: options?.actorId,\n },\n rbac\n );\n\n logger.debug(`[ModuleGraph:${this.productName}] Published ${eventType} for ${entity.type}:${entity.id}`, {\n hasRbac: !!rbac,\n });\n } catch (error) {\n logger.error(`[ModuleGraph:${this.productName}] Failed to publish ${eventType}:`, error);\n }\n }\n\n private async publishRelationshipEvent(\n eventType: 'relationship.created' | 'relationship.deleted',\n relationship: RelationshipEventData,\n organizationId: string,\n options?: GraphEventOptions\n ): Promise<void> {\n await this.ensureInitialized();\n\n if (!this.emitter) {\n logger.warn(`[ModuleGraph:${this.productName}] Emitter not initialized, skipping event`);\n return;\n }\n\n try {\n await this.emitter.publishEntityEvent(\n eventType as EntityEventType,\n {\n id: `${relationship.from.id}_${relationship.to.id}`,\n type: relationship.relationType,\n data: {\n from: relationship.from,\n to: relationship.to,\n metadata: relationship.metadata,\n },\n },\n {\n productName: this.productName,\n organizationId,\n actorId: options?.actorId,\n }\n );\n\n logger.debug(`[ModuleGraph:${this.productName}] Published ${eventType} for ${relationship.relationType}`);\n } catch (error) {\n logger.error(`[ModuleGraph:${this.productName}] Failed to publish ${eventType}:`, error);\n }\n }\n\n async shutdown(): Promise<void> {\n this.initialized = false;\n this.emitter = null;\n logger.info(`[ModuleGraph:${this.productName}] Shutdown complete`);\n }\n}\n\n// =============================================================================\n// FACTORY FUNCTION\n// =============================================================================\n\n/**\n * Define a module graph configuration\n *\n * This is the main entry point for configuring graph integration in a microservice.\n * It provides a unified API for schema definition, event publishing, and data export.\n *\n * @param definition - The module graph definition\n * @returns A ModuleGraph instance with all graph functionality\n *\n * @example\n * ```typescript\n * export const myGraph = defineModuleGraph({\n * moduleName: 'module-tags',\n * entities: {\n * tag: {\n * type: 'UniversalTag',\n * fields: ['id', 'name'],\n * getOrgId: (d) => d.tenantId as string,\n * fetch: async () => db.tag.findMany(),\n * },\n * },\n * });\n *\n * // In providers:\n * await myGraph.events.tag.created(tagData);\n *\n * // In index.ts:\n * await myGraph.initialize();\n * ```\n */\nexport function defineModuleGraph(definition: ModuleGraphDefinition): ModuleGraph {\n const { moduleName, productSource, entities, relationships = {} } = definition;\n const publisher = new GraphEventsPublisherInternal(productSource ?? moduleName);\n\n // Build entity event methods\n const events: Record<string, EntityEventMethods> = {};\n\n for (const [entityName, entityDef] of Object.entries(entities)) {\n const getOrgId = entityDef.getOrgId || ((): string | undefined => undefined);\n const getWorkspaceId = entityDef.getWorkspaceId || ((): string | undefined => undefined);\n\n // Create event context for hooks\n const createEventContext = (): EntityEventContext => ({\n publishRelationship: async (data: RelationshipEventData, orgId?: string): Promise<void> => {\n await publisher.publishRelationshipCreated(data, orgId || 'unknown');\n },\n deleteRelationship: async (data: RelationshipEventData, orgId?: string): Promise<void> => {\n await publisher.publishRelationshipDeleted(data, orgId || 'unknown');\n },\n getOrgId,\n getWorkspaceId,\n });\n\n // Build RBAC metadata extractor from entity config\n const buildRbacMetadata = (data: Record<string, unknown>): EntityEventRbacMetadata | undefined => {\n if (!entityDef.rbac) return undefined;\n const rbacConfig = entityDef.rbac;\n if (rbacConfig.createResource === false) return undefined;\n\n const entityId = data['id'] as string;\n const title = (data['name'] as string) || (data['title'] as string) || (data['label'] as string) || entityId;\n\n return {\n resourceTypeName: rbacConfig.resourceTypeName,\n name: rbacConfig.extractName?.(data) ?? title,\n identifier: rbacConfig.extractIdentifier?.(data) ?? entityId,\n parentResourceIdentifier: rbacConfig.parentResourceField\n ? (data[rbacConfig.parentResourceField] as string | undefined)\n : undefined,\n createResource: rbacConfig.createResource ?? true,\n };\n };\n\n events[entityName] = {\n created: async (data: Record<string, unknown>, options?: GraphEventOptions): Promise<void> => {\n await publisher.publishEntityCreated(\n {\n id: data['id'] as string,\n type: entityDef.type,\n data,\n organizationId: getOrgId(data),\n workspaceId: getWorkspaceId(data),\n },\n options,\n buildRbacMetadata(data)\n );\n\n if (entityDef.onCreated) {\n await entityDef.onCreated(data, createEventContext(), options);\n }\n },\n\n updated: async (data: Record<string, unknown>, options?: GraphEventOptions): Promise<void> => {\n await publisher.publishEntityUpdated(\n {\n id: data['id'] as string,\n type: entityDef.type,\n data,\n organizationId: getOrgId(data),\n workspaceId: getWorkspaceId(data),\n },\n options,\n buildRbacMetadata(data)\n );\n\n if (entityDef.onUpdated) {\n await entityDef.onUpdated(data, createEventContext(), options);\n }\n },\n\n deleted: async (data: Record<string, unknown>, options?: GraphEventOptions): Promise<void> => {\n await publisher.publishEntityDeleted(\n {\n id: data['id'] as string,\n type: entityDef.type,\n data,\n organizationId: getOrgId(data),\n workspaceId: getWorkspaceId(data),\n },\n options,\n buildRbacMetadata(data)\n );\n\n if (entityDef.onDeleted) {\n await entityDef.onDeleted(data, createEventContext(), options);\n }\n },\n };\n }\n\n // Build schema\n const getSchema = (): GraphSchema => {\n const entitySchema: Record<string, { fields: string[]; collection: string }> = {};\n const relationshipSchema: Record<string, { fromType: string; toType: string; edgeType: string }> = {};\n\n for (const [, entityDef] of Object.entries(entities)) {\n entitySchema[entityDef.type] = {\n fields: entityDef.fields || ['id', 'createdAt', 'updatedAt'],\n collection: entityDef.collection || 'entity',\n };\n }\n\n for (const [relName, relDef] of Object.entries(relationships)) {\n relationshipSchema[relName] = {\n fromType: relDef.fromType,\n toType: relDef.toType,\n edgeType: relDef.edgeType,\n };\n }\n\n return { moduleName, entities: entitySchema, relationships: relationshipSchema };\n };\n\n // Export entities\n const exportEntities = async (\n organizationId?: string,\n workspaceId?: string,\n entityTypes?: string[]\n ): Promise<Record<string, EntityExport[]>> => {\n const result: Record<string, EntityExport[]> = {};\n\n for (const [entityName, entityDef] of Object.entries(entities)) {\n if (entityTypes && !entityTypes.includes(entityDef.type)) {\n continue;\n }\n\n if (!entityDef.fetch) {\n result[entityDef.type] = [];\n continue;\n }\n\n try {\n const items = await entityDef.fetch(organizationId, workspaceId);\n result[entityDef.type] = items.map((item) => {\n const {\n id,\n createdAt,\n updatedAt,\n workspaceId: ws,\n tenantId,\n ...data\n } = item as {\n id: string;\n createdAt: Date | string;\n updatedAt: Date | string;\n workspaceId?: string;\n tenantId?: string;\n [key: string]: unknown;\n };\n\n return {\n id,\n type: entityDef.type,\n data,\n organizationId: tenantId,\n workspaceId: ws,\n createdAt: createdAt instanceof Date ? createdAt.toISOString() : String(createdAt),\n updatedAt: updatedAt instanceof Date ? updatedAt.toISOString() : String(updatedAt),\n };\n });\n } catch (error) {\n logger.error(`[ModuleGraph:${moduleName}] Error fetching ${entityName}:`, error);\n result[entityDef.type] = [];\n }\n }\n\n return result;\n };\n\n // Export relationships\n const exportRelationships = async (organizationId?: string, workspaceId?: string): Promise<RelationshipExport[]> => {\n const result: RelationshipExport[] = [];\n\n for (const [relName, relDef] of Object.entries(relationships)) {\n if (!relDef.fetch) {\n continue;\n }\n\n try {\n const items = await relDef.fetch(organizationId, workspaceId);\n for (const item of items) {\n result.push({\n id: item.id,\n type: relDef.edgeType,\n fromId: item.fromId,\n fromType: relDef.fromType,\n toId: item.toId,\n toType: relDef.toType,\n metadata: item.metadata || {},\n createdAt: item.createdAt || new Date().toISOString(),\n updatedAt: item.updatedAt || new Date().toISOString(),\n });\n }\n } catch (error) {\n logger.error(`[ModuleGraph:${moduleName}] Error fetching relationship ${relName}:`, error);\n }\n }\n\n return result;\n };\n\n // Export all\n const exportAll = async (organizationId?: string, workspaceId?: string): Promise<ExportResponse> => {\n const schema = getSchema();\n const entitiesData = await exportEntities(organizationId, workspaceId);\n const relationshipsData = await exportRelationships(organizationId, workspaceId);\n\n const entityCounts: Record<string, number> = {};\n let totalEntities = 0;\n\n for (const [type, items] of Object.entries(entitiesData)) {\n entityCounts[type] = items.length;\n totalEntities += items.length;\n }\n\n return {\n moduleName,\n productSource: productSource ?? moduleName,\n exportedAt: new Date().toISOString(),\n schema,\n data: {\n entities: entitiesData,\n relationships: relationshipsData,\n },\n stats: {\n totalEntities,\n totalRelationships: relationshipsData.length,\n entityCounts,\n },\n };\n };\n\n return {\n moduleName,\n events,\n initialize: () => publisher.initialize(),\n shutdown: () => publisher.shutdown(),\n getSchema,\n exportEntities,\n exportRelationships,\n exportAll,\n getPublisher: () => publisher,\n };\n}\n\n// =============================================================================\n// RE-EXPORT TYPES FOR CONVENIENCE\n// =============================================================================\n\nexport type {\n EntityExport as GraphEntityExport,\n RelationshipExport as GraphRelationshipExport,\n ExportResponse as GraphExportResponse,\n GraphSchema,\n};\n","/**\n * Graph Configuration Builder\n *\n * Provides the defineGraphConfig() function with full type inference.\n * This is the ONLY function developers use in their microservice.\n *\n * @module graph/config/builder\n * @category Graph\n */\n\nimport type {\n GenericGraphConfig,\n GenericEntityConfig,\n GenericRelationshipConfig,\n GraphValidationResult,\n GraphValidationError,\n FieldMapper,\n} from './types.js';\nimport { logger } from '../../logger/index.js';\nimport { GraphRegistry } from '../utils/registry.js';\nimport type { EntityGraphConfig, RelationshipGraphConfig } from '../types.js';\n\n/**\n * Standard field presets for automatic inclusion\n */\nexport const STANDARD_FIELDS = ['id', 'createdAt', 'updatedAt'] as const;\nexport const SOFT_DELETE_FIELDS = ['deletedAt'] as const;\nexport const AUDIT_FIELDS = ['metadata', 'context'] as const;\nexport const TENANT_FIELDS = ['workspaceId', 'tenantId'] as const;\n\n/**\n * Smart default implementations\n */\n\n/**\n * Default getWorkspaceId - reads workspaceId field directly\n */\nconst DEFAULT_GET_WORKSPACE_ID: FieldMapper<string> = (data) => data['workspaceId'] as string | undefined;\n\n/**\n * Default getOrgId - tries tenantId first, then context.organizationId\n * This handles both direct tenantId fields and context-based organization references\n */\nconst DEFAULT_GET_ORG_ID: FieldMapper<string> = (data) => {\n // Try tenantId first (direct field pattern used in tags service)\n if (data['tenantId']) {\n return data['tenantId'] as string;\n }\n\n // Fallback to context.organizationId (pattern used in vibecontrols)\n const context = data['context'] as Record<string, unknown> | undefined;\n return context?.['organizationId'] as string | undefined;\n};\n\n/**\n * Default extractTitle - generates {entityType}_{id} pattern\n *\n * This provides a consistent, unambiguous title for all entities.\n * For example: workspace_abc123, agent_xyz789, session_def456\n *\n * The entityType is passed in via the entity configuration context.\n */\nfunction createDefaultExtractTitle(entityType: string): FieldMapper<string> {\n return (data) => {\n const id = data['id'];\n if (typeof id === 'string' && id.length > 0) {\n return `${entityType.toLowerCase()}_${id}`;\n }\n return undefined;\n };\n}\n\n/**\n * Generate relationship label from camelCase name to SCREAMING_SNAKE_CASE\n * Example: TagToVocabulary → TAG_TO_VOCABULARY\n */\nfunction generateRelationshipLabel(relationshipName: string): string {\n return relationshipName\n .replace(/([A-Z])/g, '_$1')\n .toUpperCase()\n .replace(/^_/, '');\n}\n\n/**\n * Extract fields from Prisma model, excluding SDK defaults\n *\n * This function auto-extracts scalar fields from a Prisma model using the\n * generated prisma-fields.ts, then applies exclusions and inclusions.\n *\n * @param modelName - Prisma model name (e.g., 'User', 'Project', 'Agent')\n * @param options - Field extraction options\n * @param prismaFieldsModule - Generated Prisma fields module\n * @returns Array of field names for the entity\n */\nfunction extractFieldsFromModel(\n modelName: string,\n options: {\n exclude?: string[];\n include?: string[];\n softDelete?: boolean;\n multiTenant?: boolean;\n audit?: boolean;\n },\n prismaFieldsModule: PrismaFieldsModule\n): string[] {\n // Verify model exists\n if (!prismaFieldsModule.hasModel(modelName)) {\n const availableModels = prismaFieldsModule.getAllModelNames().join(', ');\n throw new Error(`Prisma model '${modelName}' not found. Available models: ${availableModels}`);\n }\n\n // Get all scalar fields from Prisma model\n const allFields = prismaFieldsModule.getScalarFields(modelName);\n\n // Build SDK default fields that will be auto-added (so we exclude them from Prisma extraction)\n const sdkDefaults = [\n ...STANDARD_FIELDS, // id, createdAt, updatedAt\n ...(options.softDelete !== false ? SOFT_DELETE_FIELDS : []), // deletedAt\n ...(options.multiTenant !== false ? TENANT_FIELDS : []), // workspaceId, tenantId\n ...(options.audit !== false ? AUDIT_FIELDS : []), // metadata, context\n ];\n\n // Build exclusion set (SDK defaults + user exclusions)\n const excluded = new Set([...sdkDefaults, ...(options.exclude ?? [])]);\n\n // Filter out excluded fields from Prisma model\n const filteredFields = allFields.filter((field) => !excluded.has(field));\n\n // Add any explicitly included fields\n const finalFields = [...filteredFields, ...(options.include ?? [])];\n\n return finalFields;\n}\n\n/**\n * Extended entity configuration with options for auto-including fields\n */\nexport interface DefineEntityConfigOptions extends Omit<GenericEntityConfig, 'fields'> {\n /**\n * Entity-specific fields (standard fields like id, createdAt, etc. are auto-included)\n *\n * You can either:\n * 1. Manually specify fields: `fields: ['name', 'email', ...]`\n * 2. Use Prisma model name: `model: 'User'` (requires generated prisma-fields.ts)\n * 3. Use model with exclusions: `model: 'User', exclude: ['internalField']`\n *\n * When using `model`, fields are auto-extracted from Prisma schema\n */\n fields?: string[];\n\n /**\n * Prisma model name to auto-extract fields from\n *\n * Requires the burdenoff-prisma-field-generator to be configured in your Prisma schema.\n * When specified, fields are automatically extracted from the generated prisma-fields.ts\n *\n * @example\n * ```typescript\n * // Auto-extract all fields from User model\n * User: {\n * model: 'User',\n * // extractTitle, getOrgId, etc. can still be customized\n * }\n * ```\n */\n model?: string;\n\n /**\n * Fields to exclude when using `model` auto-extraction\n *\n * Useful to exclude internal/computed fields that shouldn't be in the graph\n *\n * @example\n * ```typescript\n * User: {\n * model: 'User',\n * exclude: ['passwordHash', 'internalCounter']\n * }\n * ```\n */\n exclude?: string[];\n\n /**\n * Additional fields to include beyond what's in the Prisma model\n *\n * Useful for computed/virtual fields not in the database\n *\n * @example\n * ```typescript\n * User: {\n * model: 'User',\n * include: ['fullName', 'avatarUrl']\n * }\n * ```\n */\n include?: string[];\n\n /**\n * Auto-include soft delete field (deletedAt)\n * @default true\n */\n softDelete?: boolean;\n\n /**\n * Auto-include multi-tenant fields (workspaceId, tenantId)\n * @default true\n */\n multiTenant?: boolean;\n\n /**\n * Auto-include audit fields (metadata, context)\n * @default true\n */\n audit?: boolean;\n}\n\n/**\n * Extended relationship configuration with optional fields\n */\nexport interface DefineRelationshipConfigOptions extends Omit<GenericRelationshipConfig, 'label' | 'toField'> {\n /**\n * Relationship label - auto-generated from key if not provided\n */\n label?: string;\n\n /**\n * Target field - defaults to 'id' if not provided\n * @default 'id'\n */\n toField?: string;\n}\n\n/**\n * Validate entity configuration\n *\n * Ensures the entity config has all required fields and valid functions.\n */\nfunction validateEntityConfig(entityType: string, config: GenericEntityConfig): GraphValidationError[] {\n const errors: GraphValidationError[] = [];\n\n // Check required fields\n if (!config.fields || config.fields.length === 0) {\n errors.push({\n type: 'INVALID_ENTITY_TYPE',\n entityType,\n message: `Entity '${entityType}' must have at least one field`,\n });\n }\n\n // Check getWorkspaceId is defined\n if (!config.getWorkspaceId) {\n errors.push({\n type: 'MISSING_WORKSPACE_ID',\n entityType,\n message: `Entity '${entityType}' must define getWorkspaceId() to enforce workspace boundary`,\n });\n }\n\n // Check getOrgId is defined\n if (!config.getOrgId) {\n errors.push({\n type: 'MISSING_ORG_ID',\n entityType,\n message: `Entity '${entityType}' must define getOrgId() for multi-tenant isolation`,\n });\n }\n\n return errors;\n}\n\n/**\n * Validate relationship configuration\n */\nfunction validateRelationshipConfig(\n relationshipKey: string,\n config: GenericRelationshipConfig,\n entityTypes: Set<string>\n): GraphValidationError[] {\n const errors: GraphValidationError[] = [];\n\n // Check from entity exists\n if (!entityTypes.has(config.from)) {\n errors.push({\n type: 'INVALID_RELATIONSHIP',\n relationshipKey,\n message: `Relationship '${relationshipKey}' references unknown 'from' entity: ${config.from}`,\n });\n }\n\n // Check to entity exists (unless polymorphic)\n if (config.to !== '*' && !entityTypes.has(config.to)) {\n errors.push({\n type: 'INVALID_RELATIONSHIP',\n relationshipKey,\n message: `Relationship '${relationshipKey}' references unknown 'to' entity: ${config.to}`,\n });\n }\n\n // Check polymorphic relationships have type field\n if (config.to === '*' && !config.polymorphicTypeField) {\n errors.push({\n type: 'INVALID_RELATIONSHIP',\n relationshipKey,\n message: `Polymorphic relationship '${relationshipKey}' must define polymorphicTypeField`,\n });\n }\n\n // Check required fields\n if (!config.fromField) {\n errors.push({\n type: 'INVALID_RELATIONSHIP',\n relationshipKey,\n message: `Relationship '${relationshipKey}' must define fromField`,\n });\n }\n\n if (!config.label) {\n errors.push({\n type: 'INVALID_RELATIONSHIP',\n relationshipKey,\n message: `Relationship '${relationshipKey}' must define label`,\n });\n }\n\n return errors;\n}\n\n/**\n * Validate workspace boundary enforcement\n *\n * This ensures no entity can exist without a workspace connection.\n * Special entities like Workspace and Project can be roots.\n */\nfunction validateWorkspaceBoundary(\n config: GenericGraphConfig,\n _entityTypes: Set<string>\n): { errors: GraphValidationError[]; warnings: string[] } {\n const errors: GraphValidationError[] = [];\n const warnings: string[] = [];\n\n // Track which entities are root-eligible\n const rootTypes = new Set<string>(['Workspace', 'Project', 'Organization', 'Tenant']);\n\n // Check each entity\n for (const [entityType, entityConfig] of Object.entries(config.entities)) {\n if (entityConfig.enabled === false) continue;\n\n // Root types are always valid\n if (rootTypes.has(entityType)) {\n continue;\n }\n\n // Non-root entities MUST have getWorkspaceId defined\n if (!entityConfig.getWorkspaceId) {\n errors.push({\n type: 'ORPHANED_ENTITY',\n entityType,\n message: `Entity '${entityType}' has no workspace boundary - every entity must connect to a workspace`,\n });\n continue;\n }\n\n // Check if entity has a relationship to Workspace or Project\n let hasWorkspaceLink = false;\n if (config.relationships) {\n for (const [, relConfig] of Object.entries(config.relationships)) {\n if (relConfig.enabled === false) continue;\n\n if (\n relConfig.from === entityType &&\n (relConfig.to === 'Workspace' || relConfig.to === 'Project' || rootTypes.has(relConfig.to))\n ) {\n hasWorkspaceLink = true;\n break;\n }\n }\n }\n\n if (!hasWorkspaceLink) {\n warnings.push(\n `Entity '${entityType}' has no direct relationship to Workspace/Project. ` +\n `Ensure getWorkspaceId() is correctly implemented.`\n );\n }\n }\n\n return { errors, warnings };\n}\n\n/**\n * Validate no duplicate entity types\n */\nfunction validateNoDuplicates(\n config: GenericGraphConfig,\n _entityTypes: Set<string>\n): { errors: GraphValidationError[]; warnings: string[] } {\n const errors: GraphValidationError[] = [];\n const warnings: string[] = [];\n\n const seenEntityTypes = new Set<string>();\n const relationshipLabels = new Set<string>();\n\n // Check entity types\n for (const entityType of Object.keys(config.entities)) {\n if (seenEntityTypes.has(entityType)) {\n errors.push({\n type: 'DUPLICATE_ENTITY_TYPE',\n entityType,\n message: `Duplicate entity type: ${entityType}`,\n });\n }\n seenEntityTypes.add(entityType);\n }\n\n // Check relationship labels\n if (config.relationships) {\n for (const [key, relConfig] of Object.entries(config.relationships)) {\n const label = relConfig.label;\n if (relationshipLabels.has(label)) {\n warnings.push(`Duplicate relationship label: ${label} (in ${key}). This may cause query ambiguity.`);\n }\n relationshipLabels.add(label);\n }\n }\n\n return { errors, warnings };\n}\n\n/**\n * Perform full validation of graph configuration\n */\nfunction validateGraphConfig(config: GenericGraphConfig): GraphValidationResult {\n const allErrors: GraphValidationError[] = [];\n const allWarnings: string[] = [];\n\n // Validate entities\n for (const [entityType, entityConfig] of Object.entries(config.entities)) {\n if (entityConfig.enabled === false) continue;\n const errors = validateEntityConfig(entityType, entityConfig);\n allErrors.push(...errors);\n }\n\n // Collect entity types\n const entityTypes = new Set(Object.keys(config.entities));\n\n // Validate relationships\n if (config.relationships) {\n for (const [relationshipKey, relationshipConfig] of Object.entries(config.relationships)) {\n if (relationshipConfig.enabled === false) continue;\n const errors = validateRelationshipConfig(relationshipKey, relationshipConfig, entityTypes);\n allErrors.push(...errors);\n }\n }\n\n // Validate workspace boundary\n const boundaryResult = validateWorkspaceBoundary(config, entityTypes);\n allErrors.push(...boundaryResult.errors);\n allWarnings.push(...boundaryResult.warnings);\n\n // Validate no duplicates\n const duplicateResult = validateNoDuplicates(config, entityTypes);\n allErrors.push(...duplicateResult.errors);\n allWarnings.push(...duplicateResult.warnings);\n\n return {\n valid: allErrors.length === 0,\n errors: allErrors,\n warnings: allWarnings,\n };\n}\n\n/**\n * Prisma fields module interface (from generated prisma-fields.ts)\n */\nexport interface PrismaFieldsModule {\n getScalarFields: (modelName: string) => string[];\n hasModel: (modelName: string) => boolean;\n getAllModelNames: () => string[];\n}\n\n/**\n * Extended configuration options with auto-defaults\n */\nexport interface DefineGraphConfigOptions {\n /**\n * Module name for logging and identification\n */\n moduleName: string;\n\n /**\n * Entity configurations with extended options\n */\n entities: Record<string, DefineEntityConfigOptions>;\n\n /**\n * Relationship configurations with optional fields\n */\n relationships?: Record<string, DefineRelationshipConfigOptions>;\n\n /**\n * Optional Prisma fields module for auto-extraction\n *\n * Import from your generated prisma-fields.ts to enable model-based field extraction:\n *\n * @example\n * ```typescript\n * import * as prismaFields from './generated/prisma-fields.js';\n * import { defineGraphConfig } from '@burdenoff/be-sdk/graph';\n *\n * export const graphConfig = defineGraphConfig({\n * moduleName: 'module-users',\n * prismaFieldsModule: prismaFields,\n * entities: {\n * User: {\n * model: 'User', // Auto-extract fields from Prisma model\n * exclude: ['passwordHash'],\n * },\n * },\n * });\n * ```\n */\n prismaFieldsModule?: PrismaFieldsModule;\n}\n\n/**\n * Define graph configuration for a microservice\n *\n * This is the ONLY function developers need to call in their microservice.\n * It provides full type inference, validation, and intelligent defaults.\n *\n * **Automatic Defaults Applied**:\n * - **Collection**: Defaults to 'entities' for all entities\n * - **Standard Fields**: Auto-includes id, createdAt, updatedAt\n * - **Soft Delete**: Auto-includes deletedAt (disable with `softDelete: false`)\n * - **Multi-Tenant**: Auto-includes workspaceId, tenantId (disable with `multiTenant: false`)\n * - **Audit**: Auto-includes metadata, context (disable with `audit: false`)\n * - **getWorkspaceId**: Reads data['workspaceId'] (can override)\n * - **getOrgId**: Tries data['tenantId'], then data['context']['organizationId'] (can override)\n * - **extractTitle**: Generates {entityType}_{id} pattern (e.g., user_abc123) (can override)\n * - **toField**: Defaults to 'id' for relationships (can override)\n * - **label**: Auto-generates from relationship name (e.g., UserToProject → USER_TO_PROJECT)\n * - **multiTenant: false**: Automatically sets getWorkspaceId/getOrgId to return undefined\n *\n * @param config - The graph configuration with extended options\n * @returns Fully resolved configuration with all defaults applied\n *\n * @example\n * ```typescript\n * // BEFORE - Old approach with explicit everything\n * export const graphConfig = defineGraphConfig({\n * moduleName: 'module-users',\n * entities: {\n * User: {\n * collection: 'entities',\n * fields: ['id', 'email', 'name', 'workspaceId', 'tenantId', 'context', 'createdAt', 'updatedAt'],\n * getWorkspaceId: (data) => data.workspaceId as string,\n * getOrgId: (data) => data.tenantId as string,\n * extractTitle: (data) => data.name as string,\n * },\n * },\n * relationships: {\n * UserToProject: {\n * from: 'User',\n * to: 'Project',\n * fromField: 'projectId',\n * toField: 'id',\n * label: 'BELONGS_TO_PROJECT',\n * },\n * },\n * });\n *\n * // AFTER - New approach with intelligent defaults + model extraction\n * export const graphConfig = defineGraphConfig({\n * moduleName: 'module-users',\n * prismaFieldsModule: prismaFields, // Enable model-based extraction\n * entities: {\n * User: {\n * model: 'User', // Auto-extracts all fields from Prisma model\n * // All defaults auto-applied:\n * // - collection: 'entities'\n * // - Standard fields: id, createdAt, updatedAt\n * // - Multi-tenant: workspaceId, tenantId\n * // - Audit: metadata, context\n * // - getWorkspaceId: reads workspaceId\n * // - getOrgId: tries tenantId, then context.organizationId\n * // - extractTitle: generates user_{id} pattern\n * },\n * },\n * relationships: {\n * UserToProject: {\n * from: 'User',\n * to: 'Project',\n * fromField: 'projectId',\n * description: 'User belongs to a project',\n * // Auto-defaults:\n * // - toField: 'id'\n * // - label: 'USER_TO_PROJECT' (generated from key name)\n * },\n * },\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Custom overrides when needed\n * export const graphConfig = defineGraphConfig({\n * moduleName: 'module-projects',\n * prismaFieldsModule: prismaFields,\n * entities: {\n * ProjectRelation: {\n * model: 'ProjectRelation',\n * multiTenant: false, // Auto-sets getWorkspaceId/getOrgId to undefined\n * extractTitle: (data) => `Relation: ${data.type}`, // Custom title\n * },\n * },\n * relationships: {\n * ProjectHierarchy: {\n * from: 'Project',\n * to: 'Project',\n * fromField: 'parentId',\n * label: 'HAS_PARENT', // Override auto-generated 'PROJECT_HIERARCHY'\n * extractMetadata: (data) => ({ depth: data.depth }),\n * },\n * },\n * });\n * ```\n */\n/**\n * Process a single entity configuration with smart defaults\n */\nfunction processEntityConfig(\n entityName: string,\n entityOptions: DefineEntityConfigOptions,\n prismaFieldsModule: PrismaFieldsModule | undefined\n): GenericEntityConfig {\n const {\n softDelete = true,\n multiTenant = true,\n audit = true,\n fields,\n model,\n exclude,\n include,\n collection,\n getWorkspaceId,\n getOrgId,\n extractTitle,\n rbac,\n ...rest\n } = entityOptions;\n\n // Determine entity-specific fields (either from model or manual)\n let entityFields: string[];\n\n if (model) {\n // Auto-extract from Prisma model\n if (!prismaFieldsModule) {\n throw new Error(\n `Entity '${entityName}' uses model='${model}' but prismaFieldsModule is not provided. ` +\n `Import prisma-fields.ts and pass it to defineGraphConfig({ prismaFieldsModule: ... })`\n );\n }\n\n entityFields = extractFieldsFromModel(\n model,\n { exclude, include, softDelete, multiTenant, audit },\n prismaFieldsModule\n );\n } else if (fields) {\n // Manual field specification\n entityFields = fields;\n } else {\n throw new Error(`Entity '${entityName}' must specify either 'fields' or 'model' for field definition`);\n }\n\n // Build auto-included SDK default fields\n const autoFields: string[] = [\n ...STANDARD_FIELDS, // id, createdAt, updatedAt\n ...(softDelete ? SOFT_DELETE_FIELDS : []), // deletedAt\n ...(multiTenant ? TENANT_FIELDS : []), // workspaceId, tenantId\n ...(audit ? AUDIT_FIELDS : []), // metadata, context\n ];\n\n // Merge and deduplicate fields\n const mergedFields = [...new Set([...autoFields, ...entityFields])];\n\n // Handle multiTenant: false\n const finalGetWorkspaceId =\n multiTenant === false\n ? (_data: Record<string, unknown>) => undefined\n : (getWorkspaceId ?? DEFAULT_GET_WORKSPACE_ID);\n\n const finalGetOrgId =\n multiTenant === false ? (_data: Record<string, unknown>) => undefined : (getOrgId ?? DEFAULT_GET_ORG_ID);\n\n return {\n collection: collection ?? 'entities',\n fields: mergedFields,\n getWorkspaceId: finalGetWorkspaceId,\n getOrgId: finalGetOrgId,\n extractTitle: extractTitle ?? createDefaultExtractTitle(entityName),\n ...(rbac && { rbac }),\n ...rest,\n };\n}\n\n/**\n * Process all relationships with smart defaults\n */\nfunction processRelationships(\n relationshipOptions: Record<string, DefineRelationshipConfigOptions>\n): Record<string, GenericRelationshipConfig> {\n const relationships: Record<string, GenericRelationshipConfig> = {};\n\n for (const [relationshipName, options] of Object.entries(relationshipOptions)) {\n const { label, toField, ...rest } = options;\n\n relationships[relationshipName] = {\n toField: toField ?? 'id',\n label: label ?? generateRelationshipLabel(relationshipName),\n ...rest,\n };\n }\n\n return relationships;\n}\n\n/**\n * Log validation results and throw on errors\n */\nfunction logValidationResults(moduleName: string, validationResult: GraphValidationResult): void {\n if (validationResult.errors.length > 0) {\n logger.error(`[GraphConfig:${moduleName}] Configuration validation failed:`);\n for (const error of validationResult.errors) {\n logger.error(` - ${error.message}`, {\n type: error.type,\n entityType: error.entityType,\n relationshipKey: error.relationshipKey,\n });\n }\n throw new Error(`Graph configuration validation failed for ${moduleName}`);\n }\n\n if (validationResult.warnings.length > 0) {\n logger.warn(`[GraphConfig:${moduleName}] Configuration warnings:`);\n for (const warning of validationResult.warnings) {\n logger.warn(` - ${warning}`);\n }\n }\n\n logger.info(`[GraphConfig:${moduleName}] Configuration validated successfully`, {\n valid: validationResult.valid,\n errorCount: validationResult.errors.length,\n warningCount: validationResult.warnings.length,\n autoFieldsApplied: true,\n });\n}\n\nexport function defineGraphConfig(options: DefineGraphConfigOptions): GenericGraphConfig {\n // Process entities with smart defaults\n const entities: Record<string, GenericEntityConfig> = {};\n\n for (const [entityName, entityOptions] of Object.entries(options.entities)) {\n entities[entityName] = processEntityConfig(entityName, entityOptions, options.prismaFieldsModule);\n }\n\n // Process relationships with smart defaults\n const relationships = options.relationships ? processRelationships(options.relationships) : {};\n\n // Build final config\n const config: GenericGraphConfig = {\n moduleName: options.moduleName,\n entities,\n relationships,\n };\n\n // Validate configuration and log results\n const validationResult = validateGraphConfig(config);\n logValidationResults(config.moduleName, validationResult);\n\n // Auto-register with GraphRegistry so the Prisma graph extension\n // can emit events for these entity types without requiring explicit\n // initializeGraph() calls. This makes graph event emission work\n // automatically for any service that has a graph.config.ts.\n autoRegisterWithRegistry(config);\n\n return config;\n}\n\n/**\n * Auto-register graph config entities with GraphRegistry\n * Called automatically by defineGraphConfig() so Prisma graph extension\n * knows which entity types to monitor.\n */\nfunction autoRegisterWithRegistry(config: GenericGraphConfig): void {\n const { moduleName, entities, relationships = {} } = config;\n\n // Convert to registry format\n const registryEntities: Record<string, EntityGraphConfig> = {};\n for (const [entityType, entityConfig] of Object.entries(entities)) {\n registryEntities[entityType] = {\n fields: entityConfig.fields,\n collection: entityConfig.collection || 'entities',\n extractTitle: entityConfig.extractTitle,\n getOrgId: entityConfig.getOrgId,\n getWorkspaceId: entityConfig.getWorkspaceId,\n enabled: entityConfig.enabled,\n // Pass through RBAC config so the Prisma graph extension\n // can include RBAC metadata in entity lifecycle events\n ...(entityConfig.rbac && {\n rbac: {\n resourceTypeName: entityConfig.rbac.resourceTypeName,\n extractName: entityConfig.rbac.extractName,\n extractIdentifier: entityConfig.rbac.extractIdentifier,\n parentResourceField: entityConfig.rbac.parentResourceField,\n createResource: entityConfig.rbac.createResource,\n },\n }),\n } as EntityGraphConfig;\n }\n\n const registryRelationships: Record<string, RelationshipGraphConfig> = {};\n for (const [key, relConfig] of Object.entries(relationships)) {\n registryRelationships[key] = {\n from: relConfig.from,\n to: relConfig.to,\n fromField: relConfig.fromField,\n toField: relConfig.toField,\n label: relConfig.label,\n description: relConfig.description,\n extractMetadata: relConfig.extractMetadata,\n polymorphicTypeField: relConfig.polymorphicTypeField,\n enabled: relConfig.enabled,\n };\n }\n\n GraphRegistry.registerModule({\n moduleName,\n entities: registryEntities,\n relationships: registryRelationships,\n });\n\n logger.info(\n `[GraphConfig:${moduleName}] Auto-registered ${Object.keys(entities).length} entities with GraphRegistry`\n );\n}\n\n/**\n * Helper to create entity config with type safety\n *\n * This is optional but provides better autocomplete in IDEs.\n */\nexport function defineEntity(config: GenericEntityConfig): GenericEntityConfig {\n return config;\n}\n\n/**\n * Helper to create relationship config with type safety\n */\nexport function defineRelationship(config: GenericRelationshipConfig): GenericRelationshipConfig {\n return config;\n}\n\n/**\n * Re-export types for convenience\n */\nexport type {\n GenericGraphConfig,\n GenericEntityConfig,\n GenericRelationshipConfig,\n GraphValidationResult,\n GraphValidationError,\n};\n","/**\n * Graph Initialization System\n *\n * Handles registration of graph config with GraphRegistry and\n * automatic Prisma extension setup.\n *\n * @module graph/config/init\n * @category Graph\n */\n\nimport type { GenericGraphConfig } from './types.js';\nimport type { GraphEventEmitter } from '../middleware/prisma-extension.js';\nimport { GraphRegistry } from '../utils/registry.js';\nimport { addGraphExtension } from '../middleware/prisma-extension.js';\nimport { logger } from '../../logger/index.js';\n\n/**\n * Options for graph initialization\n */\nexport interface InitializeGraphOptions {\n /**\n * Product/module name for event metadata\n * @example 'module-tags', 'module-calendar'\n */\n productName: string;\n\n /**\n * Event emitter for publishing graph events\n * Must implement the GraphEventEmitter interface\n */\n eventEmitter: GraphEventEmitter;\n\n /**\n * Entity types to monitor (if empty, monitors all)\n * @default [] (all entities)\n */\n monitoredEntityTypes?: string[];\n\n /**\n * Whether to enable the Prisma extension\n * @default true\n */\n enabled?: boolean;\n\n /**\n * Whether to validate entity data at runtime\n * This adds overhead but catches configuration errors early\n * @default true in development, false in production\n */\n validateRuntime?: boolean;\n}\n\n/**\n * Runtime validator for entity data\n *\n * Validates that extracted data matches configuration expectations.\n * Only runs if validateRuntime is enabled.\n */\nclass RuntimeValidator {\n constructor(private config: GenericGraphConfig) {}\n\n /**\n * Validate entity data extraction\n */\n validateEntityData(\n entityType: string,\n data: Record<string, unknown>\n ): {\n valid: boolean;\n errors: string[];\n } {\n const errors: string[] = [];\n const entityConfig = this.config.entities[entityType];\n\n if (!entityConfig) {\n return { valid: true, errors: [] }; // Not configured, skip validation\n }\n\n // Check workspace ID\n try {\n const workspaceId = entityConfig.getWorkspaceId(data);\n if (!workspaceId) {\n errors.push(`Entity ${entityType}:${data['id']} has no workspaceId`);\n }\n } catch (error) {\n errors.push(`Error extracting workspaceId for ${entityType}: ${error}`);\n }\n\n // Check org ID\n try {\n const orgId = entityConfig.getOrgId(data);\n if (!orgId) {\n errors.push(`Entity ${entityType}:${data['id']} has no organizationId`);\n }\n } catch (error) {\n errors.push(`Error extracting organizationId for ${entityType}: ${error}`);\n }\n\n // Check configured fields exist\n for (const field of entityConfig.fields) {\n if (!(field in data)) {\n errors.push(`Entity ${entityType}:${data['id']} missing configured field: ${field}`);\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n }\n}\n\n/**\n * Initialize graph integration for a microservice\n *\n * This function:\n * 1. Registers the configuration with GraphRegistry\n * 2. Sets up the Prisma extension for automatic event emission\n * 3. Validates workspace boundaries\n * 4. Returns an extended Prisma client\n *\n * @param prismaClient - Base Prisma client instance\n * @param config - Graph configuration from defineGraphConfig()\n * @param options - Initialization options\n * @returns Extended Prisma client with graph event emission\n *\n * @example\n * ```typescript\n * // microservice/src/index.ts\n * import { PrismaClient } from '@prisma/client';\n * import { initializeGraph } from '@burdenoff/be-sdk/graph';\n * import { graphConfig } from './graph.config.js';\n * import { graphEventEmitter } from './events.js';\n *\n * const basePrisma = new PrismaClient();\n *\n * const prisma = initializeGraph(basePrisma, graphConfig, {\n * productName: 'module-tags',\n * eventEmitter: graphEventEmitter,\n * });\n *\n * // Now use prisma normally - events are emitted automatically\n * const tag = await prisma.universalTag.create({\n * data: { name: 'Important', workspaceId: '...' }\n * });\n * // -> entity.created event emitted automatically\n * // -> relationship.created event emitted if vocabularyId is set\n * ```\n */\nexport function initializeGraph<TPrisma>(\n prismaClient: TPrisma,\n config: GenericGraphConfig,\n options: InitializeGraphOptions\n): TPrisma {\n const { productName, eventEmitter, monitoredEntityTypes = [], enabled = true, validateRuntime } = options;\n\n // Determine if runtime validation should be enabled\n const shouldValidate = validateRuntime ?? process.env['NODE_ENV'] !== 'production';\n\n logger.info(`[GraphInit:${config.moduleName}] Initializing graph integration`, {\n productName,\n enabled,\n validateRuntime: shouldValidate,\n entities: Object.keys(config.entities).length,\n relationships: config.relationships ? Object.keys(config.relationships).length : 0,\n });\n\n if (!enabled) {\n logger.warn(`[GraphInit:${config.moduleName}] Graph integration disabled by configuration`);\n return prismaClient;\n }\n\n // Step 1: Register configuration with GraphRegistry\n registerConfigWithRegistry(config);\n\n // Step 2: Create runtime validator if enabled\n const validator = shouldValidate ? new RuntimeValidator(config) : null;\n\n // Step 3: Wrap event emitter with validation\n const wrappedEmitter: GraphEventEmitter = {\n publishEntityEvent: async (eventType, entity, context, rbac) => {\n // Runtime validation\n if (validator && (eventType === 'entity.created' || eventType === 'entity.updated')) {\n const validation = validator.validateEntityData(entity.type, entity.data);\n if (!validation.valid) {\n logger.error(`[GraphInit:${config.moduleName}] Runtime validation failed for ${entity.type}:${entity.id}`, {\n errors: validation.errors,\n });\n // Continue anyway - we log but don't block\n }\n }\n\n // Forward to actual emitter\n return eventEmitter.publishEntityEvent(eventType, entity, context, rbac);\n },\n };\n\n // Step 4: Add Prisma extension\n const extendedClient = addGraphExtension(prismaClient, {\n enabled: true,\n productName,\n eventEmitter: wrappedEmitter,\n entityTypes: monitoredEntityTypes,\n });\n\n logger.info(`[GraphInit:${config.moduleName}] Graph integration initialized successfully`);\n\n return extendedClient;\n}\n\n/**\n * Register configuration with GraphRegistry\n *\n * Converts GenericGraphConfig to ModuleGraphConfig format\n * that GraphRegistry expects.\n */\nfunction registerConfigWithRegistry(config: GenericGraphConfig): void {\n const { moduleName, entities, relationships = {} } = config;\n\n // Convert GenericEntityConfig to EntityGraphConfig\n const registryEntities: Record<\n string,\n {\n fields: string[];\n collection?: string;\n extractTitle?: (entity: Record<string, unknown>) => string | undefined;\n getOrgId?: (data: Record<string, unknown>) => string | undefined;\n getWorkspaceId?: (data: Record<string, unknown>) => string | undefined;\n enabled?: boolean;\n }\n > = {};\n\n for (const [entityType, entityConfig] of Object.entries(entities)) {\n registryEntities[entityType] = {\n fields: entityConfig.fields,\n collection: entityConfig.collection || 'entities',\n extractTitle: entityConfig.extractTitle,\n getOrgId: entityConfig.getOrgId,\n getWorkspaceId: entityConfig.getWorkspaceId,\n enabled: entityConfig.enabled,\n };\n }\n\n // Convert GenericRelationshipConfig to RelationshipGraphConfig\n const registryRelationships: Record<\n string,\n {\n from: string;\n to: string;\n fromField: string;\n toField?: string;\n label: string;\n description?: string;\n extractMetadata?: (record: Record<string, unknown>) => Record<string, unknown>;\n polymorphicTypeField?: string;\n enabled?: boolean;\n }\n > = {};\n\n for (const [key, relConfig] of Object.entries(relationships)) {\n registryRelationships[key] = {\n from: relConfig.from,\n to: relConfig.to,\n fromField: relConfig.fromField,\n toField: relConfig.toField,\n label: relConfig.label,\n description: relConfig.description,\n extractMetadata: relConfig.extractMetadata,\n polymorphicTypeField: relConfig.polymorphicTypeField,\n enabled: relConfig.enabled,\n };\n }\n\n // Register with GraphRegistry\n GraphRegistry.registerModule({\n moduleName,\n entities: registryEntities as Record<string, import('../types.js').EntityGraphConfig>,\n relationships: registryRelationships,\n });\n\n logger.info(`[GraphInit:${moduleName}] Configuration registered with GraphRegistry`);\n}\n\n/**\n * Validate that a Prisma client has been properly initialized with graph support\n *\n * This is a runtime check to ensure initializeGraph() was called.\n *\n * @param moduleName - Module name for logging\n * @returns Whether the module is registered\n */\nexport function isGraphInitialized(moduleName: string): boolean {\n const registeredModules = GraphRegistry.getRegisteredModules();\n return registeredModules.includes(moduleName);\n}\n\n/**\n * Get graph statistics for a module\n *\n * Useful for debugging and monitoring.\n */\nexport function getGraphStats(): {\n modules: number;\n entities: number;\n relationships: number;\n registeredModules: string[];\n} {\n const stats = GraphRegistry.getStats();\n const registeredModules = GraphRegistry.getRegisteredModules();\n\n return {\n modules: stats.modules,\n entities: stats.entities,\n relationships: stats.relationships,\n registeredModules,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/graph/index.ts","../src/graph/utils/prisma-helpers.ts","../src/graph/events-helper.ts","../src/graph/export-service.ts","../src/graph/module-graph.ts","../src/graph/config/builder.ts","../src/graph/config/init.ts"],"names":["createPrismaGraphIntegration","options","serviceName","graphConfig","productName","validateRuntime","process","env","NODE_ENV","autoInit","createPrismaClient","ensureServiceApplicationName","state","graphEmitter","extendedPrismaClient","emitterInitialized","initializationPromise","initializeGraphEmitter","logger","info","GraphEventEmitterImpl","basePrisma","initializeGraph","eventEmitter","enabled","error","db","warn","baseClient","client","prisma","Proxy","get","_","prop","value","bind","cleanup","disconnect","$disconnect","getGraphEmitter","isInitialized","GraphEventsPublisher","instance","initialized","emitter","getInstance","setProductName","name","initialize","getGraphEventEmitter","natsUrl","ensureInitialized","publishEntityCreated","entity","publishEntityEvent","publishEntityUpdated","publishEntityDeleted","publishRelationshipCreated","relationship","organizationId","publishRelationshipEvent","publishRelationshipDeleted","eventType","id","type","data","workspaceId","actorId","userId","debug","from","to","relationType","metadata","shutdown","reset","getGraphEventsPublisher","createGraphEventsHelper","config","publisher","moduleName","helper","entityConfig","Object","entries","entities","created","getOrgId","getWorkspaceId","onCreated","updated","onUpdated","deleted","onDeleted","GraphExportService","fetchers","relationshipFetchers","customTransformer","serviceConfig","transformEntity","getSchema","relationships","entityType","fields","Array","isArray","collection","relType","fromType","toType","edgeType","label","exportEntities","entityTypes","result","typesToExport","keys","fetcher","map","item","exportRelationships","rels","push","exportAll","schema","entityCounts","totalEntities","items","length","productSource","exportedAt","Date","toISOString","stats","totalRelationships","createdAt","updatedAt","tenantId","String","createGraphExportService","createRelationshipFromEntity","relationConfig","fromId","toId","extractMetadata","GraphEventsPublisherInternal","rbac","hasRbac","defineModuleGraph","definition","events","entityName","entityDef","undefined","createEventContext","publishRelationship","orgId","deleteRelationship","buildRbacMetadata","rbacConfig","createResource","entityId","title","resourceTypeName","extractName","identifier","extractIdentifier","parentResourceIdentifier","parentResourceField","entitySchema","relationshipSchema","relName","relDef","includes","fetch","ws","entitiesData","relationshipsData","getPublisher","STANDARD_FIELDS","SOFT_DELETE_FIELDS","AUDIT_FIELDS","TENANT_FIELDS","DEFAULT_GET_WORKSPACE_ID","DEFAULT_GET_ORG_ID","context","createDefaultExtractTitle","toLowerCase","generateRelationshipLabel","relationshipName","replace","toUpperCase","extractFieldsFromModel","modelName","prismaFieldsModule","hasModel","availableModels","getAllModelNames","join","Error","allFields","getScalarFields","sdkDefaults","softDelete","multiTenant","audit","excluded","Set","exclude","filteredFields","filter","field","has","finalFields","include","validateEntityConfig","errors","message","validateRelationshipConfig","relationshipKey","polymorphicTypeField","fromField","validateWorkspaceBoundary","_entityTypes","warnings","rootTypes","hasWorkspaceLink","relConfig","validateNoDuplicates","seenEntityTypes","relationshipLabels","add","key","validateGraphConfig","allErrors","allWarnings","relationshipConfig","boundaryResult","duplicateResult","valid","processEntityConfig","entityOptions","model","extractTitle","rest","entityFields","autoFields","mergedFields","finalGetWorkspaceId","_data","finalGetOrgId","processRelationships","relationshipOptions","toField","logValidationResults","validationResult","warning","errorCount","warningCount","autoFieldsApplied","defineGraphConfig","autoRegisterWithRegistry","registryEntities","registryRelationships","description","GraphRegistry","registerModule","defineEntity","defineRelationship","RuntimeValidator","validateEntityData","prismaClient","monitoredEntityTypes","shouldValidate","registerConfigWithRegistry","validator","wrappedEmitter","validation","extendedClient","addGraphExtension","isGraphInitialized","registeredModules","getRegisteredModules","getGraphStats","getStats","modules","GraphModule","createNode","ValidationError","properties","mutation","variables","input","response","query","nodeId","createGraphNode","createEdge","edgeId","createGraphEdge","getNode","getGraphNode","updateNode","updateGraphNode","deleteNode","deleteEdge","traverse","startNode","direction","edgeTypes","minDepth","maxDepth","limit","traverseGraph","findShortestPath","fromNode","toNode","bindVars","executeCypher","results","getNeighbors","getNodeDegree","findNodes","filters","offset","findGraphNodes","createNodesBatch","nodes","count","createGraphNodesBatch","createEdgesBatch","edges","createGraphEdgesBatch"],"mappings":";;;;;;;AAAA,IAAA,aAAA,GAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACoJO,SAASA,6BACdC,OAAAA,EAAqD;AASrD,EAAA,MAAM,EACJC,WAAAA,EACAC,WAAAA,EACAC,WAAAA,GAAc,YAAA,EACdC,eAAAA,GAAkBC,OAAAA,CAAQC,GAAAA,CAAIC,QAAAA,KAAa,YAAA,EAC3CC,QAAAA,GAAW,IAAA,EACXC,oBAAkB,GAChBT,OAAAA;AAOJU,EAAAA,4BAA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AAA;AAClB,EAAA;AACF","file":"chunk-VSPK4WB7.js","sourcesContent":["/**\n * Graph Integration Module\n *\n * All operations route through the federated GraphQL schema exposed by\n * `wspace-graph-svc` (via `wspace-int-gateway`). Consuming services never\n * open a direct graph-DB connection — the underlying graph database\n * cluster is only reached through the Python sidecar inside the graph pod.\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\nexport interface GraphNode {\n id: string;\n type: string;\n properties: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface GraphEdge {\n id: string;\n from: string;\n to: string;\n type: string;\n properties?: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n createdAt: string;\n}\n\nexport interface CreateNodeOptions {\n type: string;\n properties: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n}\n\nexport interface CreateEdgeOptions {\n from: string;\n to: string;\n type: string;\n properties?: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n}\n\n/**\n * Graph traversal direction\n */\nexport type TraverseDirection = 'outbound' | 'inbound' | 'any';\n\nexport interface TraverseOptions {\n startNode: string;\n direction?: TraverseDirection;\n edgeTypes?: string[];\n minDepth?: number;\n maxDepth?: number;\n limit?: number;\n}\n\nexport interface TraverseResult {\n nodes: GraphNode[];\n edges: GraphEdge[];\n paths: Array<{\n nodes: GraphNode[];\n edges: GraphEdge[];\n }>;\n}\n\nexport interface QueryGraphOptions {\n /** openCypher query (since the 2026-05 NebulaGraph → Apache AGE migration) */\n query: string;\n /** Bind variables */\n bindVars?: Record<string, unknown>;\n /** Limit results */\n limit?: number;\n}\n\n/**\n * Graph Integration Module\n */\nexport class GraphModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Create graph node\n */\n public async createNode(options: CreateNodeOptions): Promise<GraphNode> {\n if (!options.type) {\n throw new ValidationError('Node type is required');\n }\n\n if (!options.properties || typeof options.properties !== 'object') {\n throw new ValidationError('Node properties must be an object');\n }\n\n logger.debug('[Graph] Creating node', { type: options.type });\n\n const mutation = `\n mutation CreateGraphNode($input: CreateGraphNodeInput!) {\n createGraphNode(input: $input) {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n }\n `;\n\n const variables = {\n input: {\n type: options.type,\n properties: options.properties,\n workspaceId: options.workspaceId || this.context.workspaceId,\n organizationId: options.organizationId,\n },\n };\n\n const response = await this.client.query<{ createGraphNode: GraphNode }>(mutation, variables, this.context);\n\n logger.info('[Graph] Node created', { nodeId: response.createGraphNode.id });\n\n return response.createGraphNode;\n }\n\n /**\n * Create graph edge\n */\n public async createEdge(options: CreateEdgeOptions): Promise<GraphEdge> {\n if (!options.from) {\n throw new ValidationError('Source node ID is required');\n }\n\n if (!options.to) {\n throw new ValidationError('Target node ID is required');\n }\n\n if (!options.type) {\n throw new ValidationError('Edge type is required');\n }\n\n logger.debug('[Graph] Creating edge', {\n from: options.from,\n to: options.to,\n type: options.type,\n });\n\n const mutation = `\n mutation CreateGraphEdge($input: CreateGraphEdgeInput!) {\n createGraphEdge(input: $input) {\n id\n from\n to\n type\n properties\n workspaceId\n organizationId\n createdAt\n }\n }\n `;\n\n const variables = {\n input: {\n from: options.from,\n to: options.to,\n type: options.type,\n properties: options.properties,\n workspaceId: options.workspaceId || this.context.workspaceId,\n organizationId: options.organizationId,\n },\n };\n\n const response = await this.client.query<{ createGraphEdge: GraphEdge }>(mutation, variables, this.context);\n\n logger.info('[Graph] Edge created', { edgeId: response.createGraphEdge.id });\n\n return response.createGraphEdge;\n }\n\n /**\n * Get node by ID\n */\n public async getNode(nodeId: string): Promise<GraphNode | null> {\n logger.debug('[Graph] Getting node', { nodeId });\n\n const query = `\n query GetGraphNode($nodeId: ID!) {\n getGraphNode(nodeId: $nodeId) {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.query<{ getGraphNode: GraphNode | null }>(query, { nodeId }, this.context);\n\n return response.getGraphNode;\n }\n\n /**\n * Update node\n */\n public async updateNode(nodeId: string, properties: Record<string, unknown>): Promise<GraphNode> {\n logger.debug('[Graph] Updating node', { nodeId });\n\n const mutation = `\n mutation UpdateGraphNode($nodeId: ID!, $properties: JSON!) {\n updateGraphNode(nodeId: $nodeId, properties: $properties) {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.query<{ updateGraphNode: GraphNode }>(\n mutation,\n { nodeId, properties },\n this.context\n );\n\n logger.info('[Graph] Node updated', { nodeId });\n\n return response.updateGraphNode;\n }\n\n /**\n * Delete node\n */\n public async deleteNode(nodeId: string): Promise<boolean> {\n logger.debug('[Graph] Deleting node', { nodeId });\n\n const mutation = `\n mutation DeleteGraphNode($nodeId: ID!) {\n deleteGraphNode(nodeId: $nodeId) {\n success\n }\n }\n `;\n\n await this.client.query(mutation, { nodeId }, this.context);\n\n logger.info('[Graph] Node deleted', { nodeId });\n\n return true;\n }\n\n /**\n * Delete edge\n */\n public async deleteEdge(edgeId: string): Promise<boolean> {\n logger.debug('[Graph] Deleting edge', { edgeId });\n\n const mutation = `\n mutation DeleteGraphEdge($edgeId: ID!) {\n deleteGraphEdge(edgeId: $edgeId) {\n success\n }\n }\n `;\n\n await this.client.query(mutation, { edgeId }, this.context);\n\n logger.info('[Graph] Edge deleted', { edgeId });\n\n return true;\n }\n\n /**\n * Traverse graph\n */\n public async traverse(options: TraverseOptions): Promise<TraverseResult> {\n if (!options.startNode) {\n throw new ValidationError('Start node ID is required');\n }\n\n logger.debug('[Graph] Traversing graph', {\n startNode: options.startNode,\n direction: options.direction || 'outbound',\n });\n\n const query = `\n query TraverseGraph(\n $startNode: ID!\n $direction: GraphDirection\n $edgeTypes: [String!]\n $minDepth: Int\n $maxDepth: Int\n $limit: Int\n ) {\n traverseGraph(\n startNode: $startNode\n direction: $direction\n edgeTypes: $edgeTypes\n minDepth: $minDepth\n maxDepth: $maxDepth\n limit: $limit\n ) {\n nodes {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n edges {\n id\n from\n to\n type\n properties\n workspaceId\n organizationId\n createdAt\n }\n paths {\n nodes {\n id\n type\n properties\n }\n edges {\n id\n from\n to\n type\n }\n }\n }\n }\n `;\n\n const variables = {\n startNode: options.startNode,\n direction: options.direction || 'outbound',\n edgeTypes: options.edgeTypes,\n minDepth: options.minDepth || 1,\n maxDepth: options.maxDepth || 3,\n limit: options.limit || 100,\n };\n\n const response = await this.client.query<{ traverseGraph: TraverseResult }>(query, variables, this.context);\n\n return response.traverseGraph;\n }\n\n /**\n * Find shortest path between two nodes\n */\n public async findShortestPath(\n fromNode: string,\n toNode: string,\n options?: {\n edgeTypes?: string[];\n maxDepth?: number;\n }\n ): Promise<{\n nodes: GraphNode[];\n edges: GraphEdge[];\n distance: number;\n } | null> {\n logger.debug('[Graph] Finding shortest path', { fromNode, toNode });\n\n const query = `\n query FindShortestPath(\n $fromNode: ID!\n $toNode: ID!\n $edgeTypes: [String!]\n $maxDepth: Int\n ) {\n findShortestPath(\n fromNode: $fromNode\n toNode: $toNode\n edgeTypes: $edgeTypes\n maxDepth: $maxDepth\n ) {\n nodes {\n id\n type\n properties\n }\n edges {\n id\n from\n to\n type\n }\n distance\n }\n }\n `;\n\n const response = await this.client.query<{\n findShortestPath: {\n nodes: GraphNode[];\n edges: GraphEdge[];\n distance: number;\n } | null;\n }>(\n query,\n {\n fromNode,\n toNode,\n edgeTypes: options?.edgeTypes,\n maxDepth: options?.maxDepth || 10,\n },\n this.context\n );\n\n return response.findShortestPath;\n }\n\n /**\n * Query graph with raw openCypher. Proxied to wspace-graph-svc's\n * `executeCypher` resolver via the federated GraphQL gateway — no direct\n * graph-DB access. (Pre-2026-05 this used `executeNGQL` against NebulaGraph;\n * the federated resolver was renamed during the Apache AGE migration.)\n */\n public async query<T = unknown>(options: QueryGraphOptions): Promise<T[]> {\n if (!options.query) {\n throw new ValidationError('Cypher query is required');\n }\n\n logger.debug('[Graph] Executing Cypher query');\n\n const query = `\n query ExecuteCypher($query: String!, $bindVars: JSON, $limit: Int) {\n executeCypher(query: $query, bindVars: $bindVars, limit: $limit) {\n results\n }\n }\n `;\n\n const variables = {\n query: options.query,\n bindVars: options.bindVars,\n limit: options.limit || 1000,\n };\n\n const response = await this.client.query<{ executeCypher: { results: T[] } }>(query, variables, this.context);\n\n return response.executeCypher.results;\n }\n\n /**\n * Get neighbors of a node\n */\n public async getNeighbors(\n nodeId: string,\n options?: {\n direction?: 'outbound' | 'inbound' | 'any';\n edgeTypes?: string[];\n limit?: number;\n }\n ): Promise<{\n nodes: GraphNode[];\n edges: GraphEdge[];\n }> {\n logger.debug('[Graph] Getting neighbors', { nodeId });\n\n const query = `\n query GetNeighbors(\n $nodeId: ID!\n $direction: GraphDirection\n $edgeTypes: [String!]\n $limit: Int\n ) {\n getNeighbors(\n nodeId: $nodeId\n direction: $direction\n edgeTypes: $edgeTypes\n limit: $limit\n ) {\n nodes {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n edges {\n id\n from\n to\n type\n properties\n workspaceId\n organizationId\n createdAt\n }\n }\n }\n `;\n\n const response = await this.client.query<{\n getNeighbors: {\n nodes: GraphNode[];\n edges: GraphEdge[];\n };\n }>(\n query,\n {\n nodeId,\n direction: options?.direction || 'outbound',\n edgeTypes: options?.edgeTypes,\n limit: options?.limit || 100,\n },\n this.context\n );\n\n return response.getNeighbors;\n }\n\n /**\n * Get node degree (number of connections)\n */\n public async getNodeDegree(\n nodeId: string,\n direction?: 'outbound' | 'inbound' | 'any'\n ): Promise<{\n inbound: number;\n outbound: number;\n total: number;\n }> {\n logger.debug('[Graph] Getting node degree', { nodeId });\n\n const query = `\n query GetNodeDegree($nodeId: ID!, $direction: GraphDirection) {\n getNodeDegree(nodeId: $nodeId, direction: $direction) {\n inbound\n outbound\n total\n }\n }\n `;\n\n const response = await this.client.query<{\n getNodeDegree: {\n inbound: number;\n outbound: number;\n total: number;\n };\n }>(query, { nodeId, direction }, this.context);\n\n return response.getNodeDegree;\n }\n\n /**\n * Find nodes by properties\n */\n public async findNodes(\n type: string,\n filters: Record<string, unknown>,\n options?: {\n limit?: number;\n offset?: number;\n }\n ): Promise<{\n nodes: GraphNode[];\n total: number;\n }> {\n logger.debug('[Graph] Finding nodes', { type, filters });\n\n const query = `\n query FindGraphNodes(\n $type: String!\n $filters: JSON!\n $limit: Int\n $offset: Int\n ) {\n findGraphNodes(\n type: $type\n filters: $filters\n limit: $limit\n offset: $offset\n ) {\n nodes {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n total\n }\n }\n `;\n\n const response = await this.client.query<{\n findGraphNodes: {\n nodes: GraphNode[];\n total: number;\n };\n }>(\n query,\n {\n type,\n filters,\n limit: options?.limit || 100,\n offset: options?.offset || 0,\n },\n this.context\n );\n\n return response.findGraphNodes;\n }\n\n /**\n * Batch create nodes\n */\n public async createNodesBatch(nodes: CreateNodeOptions[]): Promise<GraphNode[]> {\n logger.debug('[Graph] Batch creating nodes', { count: nodes.length });\n\n const mutation = `\n mutation CreateGraphNodesBatch($nodes: [CreateGraphNodeInput!]!) {\n createGraphNodesBatch(nodes: $nodes) {\n id\n type\n properties\n workspaceId\n organizationId\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.query<{ createGraphNodesBatch: GraphNode[] }>(mutation, { nodes }, this.context);\n\n logger.info('[Graph] Nodes batch created', { count: response.createGraphNodesBatch.length });\n\n return response.createGraphNodesBatch;\n }\n\n /**\n * Batch create edges\n */\n public async createEdgesBatch(edges: CreateEdgeOptions[]): Promise<GraphEdge[]> {\n logger.debug('[Graph] Batch creating edges', { count: edges.length });\n\n const mutation = `\n mutation CreateGraphEdgesBatch($edges: [CreateGraphEdgeInput!]!) {\n createGraphEdgesBatch(edges: $edges) {\n id\n from\n to\n type\n properties\n workspaceId\n organizationId\n createdAt\n }\n }\n `;\n\n const response = await this.client.query<{ createGraphEdgesBatch: GraphEdge[] }>(mutation, { edges }, this.context);\n\n logger.info('[Graph] Edges batch created', { count: response.createGraphEdgesBatch.length });\n\n return response.createGraphEdgesBatch;\n }\n}\n\n/**\n * Export graph services, utilities, and middleware\n */\n// Export types\nexport type {\n GraphEventType,\n GraphEvent,\n EntityVertex,\n EdgeDocument,\n EntityGraphConfig,\n RelationshipGraphConfig,\n ModuleGraphConfig,\n SearchFilters,\n SearchResult,\n ProductFacet,\n TypeFacet,\n SearchFacets,\n SearchResponse,\n} from './types.js';\n\n// NOTE: GraphSyncService / GraphQueryService / GlobalSearchService were removed\n// during the AGE migration. Consuming services should use `defineModuleGraph`\n// to publish NATS events and use the SDK gateway client for reads.\n\n// Export utilities\nexport { GraphRegistry, createPrismaGraphIntegration } from './utils/index.js';\nexport type { PrismaGraphIntegration, PrismaGraphIntegrationOptions } from './utils/index.js';\nexport {\n createEntityEvent,\n createRelationshipEvent,\n extractMinimalFields,\n parseRelationship,\n getCollectionForEntity,\n extractEntityTitle,\n shouldSyncEntity,\n shouldSyncRelationship,\n} from './utils/helpers.js';\n\n// Export middleware\nexport { addGraphExtension } from './middleware/index.js';\nexport type { EntityEventType, GraphEventEmitter, GraphMiddlewareConfig } from './middleware/index.js';\n\n// Export Graph Events Helper\nexport { GraphEventsPublisher, getGraphEventsPublisher, createGraphEventsHelper } from './events-helper.js';\nexport type {\n GraphEventPublishOptions,\n GraphRelationshipData,\n GraphEntityConfig,\n GraphEventsHelperConfig,\n EntityEventData,\n GraphEventsHelper,\n} from './events-helper.js';\n\n// Export Graph Export Service\nexport { GraphExportService, createGraphExportService, createRelationshipFromEntity } from './export-service.js';\nexport type {\n GraphEntityExport,\n GraphRelationshipExport,\n GraphExportResponse,\n EntityFetcher,\n RelationshipFetcher,\n GraphExportServiceConfig,\n} from './export-service.js';\n\n// Export Unified Module Graph (recommended approach)\nexport { defineModuleGraph } from './module-graph.js';\nexport type {\n ModuleGraph,\n ModuleGraphDefinition,\n EntityDefinition,\n RelationshipDefinition,\n EntityEventContext,\n EntityEventHook,\n GraphEventOptions,\n RelationshipEventData,\n RelationshipExportData,\n GraphSchema,\n EntityRbacConfig,\n} from './module-graph.js';\n\n// Export New Generic Graph Configuration System (RECOMMENDED)\nexport {\n defineGraphConfig,\n defineEntity,\n defineRelationship,\n STANDARD_FIELDS,\n SOFT_DELETE_FIELDS,\n AUDIT_FIELDS,\n TENANT_FIELDS,\n} from './config/builder.js';\nexport type {\n GenericGraphConfig,\n GenericEntityConfig,\n GenericRelationshipConfig,\n DefineGraphConfigOptions,\n DefineEntityConfigOptions,\n DefineRelationshipConfigOptions,\n GraphValidationResult,\n GraphValidationError,\n} from './config/builder.js';\n\n// Export Graph Initialization\nexport { initializeGraph, isGraphInitialized, getGraphStats } from './config/init.js';\nexport type { InitializeGraphOptions } from './config/init.js';\n\n// Export all config types\nexport type {\n FieldMapper,\n ValidationErrorType,\n ExtractedEntityData,\n ExtractedRelationshipData,\n EntityRbacConfig as GenericEntityRbacConfig,\n} from './config/types.js';\n","/**\n * Reusable Prisma Client Graph Integration Utilities\n *\n * Provides standardized patterns for integrating Prisma with the Graph module,\n * supporting both standard Prisma and Prisma 7 adapter patterns.\n *\n * @module @burdenoff/be-sdk/graph/utils/prisma-helpers\n */\n\nimport type { PrismaClientBase } from '../../prisma/client.js';\nimport { ensureServiceApplicationName } from '../../prisma/client.js';\nimport type { GenericGraphConfig } from '../config/types.js';\nimport { initializeGraph } from '../index.js';\nimport { GraphEventEmitterImpl } from '../../event-queue/index.js';\nimport { logger } from '../../logger/index.js';\n\n/**\n * Configuration options for Prisma graph integration\n */\nexport interface PrismaGraphIntegrationOptions<TPrismaClient = unknown> {\n /**\n * Name of the service (for logging)\n * @example 'Tags Service', 'VibeControls Service'\n */\n serviceName: string;\n\n /**\n * Graph configuration from defineGraphConfig()\n */\n graphConfig: GenericGraphConfig;\n\n /**\n * Product name for event metadata\n * @default 'workspaces'\n */\n productName?: string;\n\n /**\n * Whether to validate configuration at runtime\n * @default true in development, false in production\n */\n validateRuntime?: boolean;\n\n /**\n * Whether to automatically initialize graph emitter on first database access\n * When true, initialization happens lazily when prisma or db() is first used\n * When false, you must manually call initializeGraphEmitter()\n * @default true\n */\n autoInit?: boolean;\n\n /**\n * Factory function to create base Prisma client\n * Supports both standard and adapter patterns\n *\n * @example\n * // Standard Prisma\n * createPrismaClient: () => new PrismaClient()\n *\n * @example\n * // Prisma 7 with adapter\n * createPrismaClient: () => {\n * const pool = new Pool({ connectionString: process.env.DATABASE_URL });\n * const adapter = new PrismaPg(pool);\n * return new PrismaClient({ adapter });\n * }\n */\n createPrismaClient: () => TPrismaClient;\n}\n\n/**\n * Singleton state for graph integration\n */\ninterface GraphIntegrationState<TPrismaClient> {\n graphEmitter: GraphEventEmitterImpl | null;\n extendedPrismaClient: TPrismaClient | null;\n emitterInitialized: boolean;\n initializationPromise: Promise<void> | null;\n}\n\n/**\n * Create a reusable Prisma graph integration manager\n *\n * This factory function creates a complete set of utilities for integrating\n * Prisma with the Graph module, handling initialization, client access, and cleanup.\n *\n * @template TPrismaClient The Prisma client type (supports generic for type safety)\n * @param options Configuration options\n * @returns Object with initialization functions and client accessors\n *\n * @example\n * ```typescript\n * // Standard Prisma with auto-initialization (default)\n * import { PrismaClient as PrismaClientClass } from '@prisma/client';\n * import { createPrismaGraphIntegration } from '@burdenoff/be-sdk/graph/utils/prisma-helpers';\n * import { graphConfig } from './graph.config.js';\n *\n * const {\n * prisma\n * } = createPrismaGraphIntegration({\n * serviceName: 'Tags Service',\n * graphConfig,\n * createPrismaClient: () => new PrismaClientClass(),\n * // autoInit: true is default - initialization happens automatically\n * });\n *\n * // Just use it! Initialization happens automatically on first access\n * const tags = await prisma.universalTag.findMany();\n *\n * // If you need manual control over initialization timing:\n * const {\n * initializeGraphEmitter,\n * prisma\n * } = createPrismaGraphIntegration({\n * serviceName: 'Tags Service',\n * graphConfig,\n * createPrismaClient: () => new PrismaClientClass(),\n * autoInit: false, // Disable auto-initialization\n * });\n *\n * // In your server startup (with autoInit: false):\n * await initializeGraphEmitter();\n * ```\n *\n * @example\n * ```typescript\n * // Prisma 7 with Adapter (VibeControls Service)\n * import { Pool } from 'pg';\n * import { PrismaClient as PrismaClientClass } from '@prisma/client';\n * import { PrismaPg } from '@prisma/adapter-pg';\n * import { createPrismaGraphIntegration } from '@burdenoff/be-sdk/graph/utils/prisma-helpers';\n * import { graphConfig } from './graph.config.js';\n *\n * const {\n * initializeGraphEmitter,\n * db,\n * prisma\n * } = createPrismaGraphIntegration({\n * serviceName: 'VibeControls Service',\n * graphConfig,\n * createPrismaClient: () => {\n * const pool = new Pool({ connectionString: process.env.DATABASE_URL });\n * const adapter = new PrismaPg(pool);\n * return new PrismaClientClass({ adapter });\n * },\n * });\n * ```\n */\nexport function createPrismaGraphIntegration<TPrismaClient extends PrismaClientBase>(\n options: PrismaGraphIntegrationOptions<TPrismaClient>\n): {\n initializeGraphEmitter: () => Promise<void>;\n db: () => { client: TPrismaClient };\n prisma: TPrismaClient;\n cleanup: () => Promise<void>;\n getGraphEmitter: () => GraphEventEmitterImpl | null;\n isInitialized: () => boolean;\n} {\n const {\n serviceName,\n graphConfig,\n productName = 'workspaces',\n validateRuntime = process.env.NODE_ENV !== 'production',\n autoInit = true,\n createPrismaClient,\n } = options;\n\n // Set per-service Postgres application_name (PGAPPNAME) up-front, BEFORE the\n // caller's `createPrismaClient` closure constructs its own pg Pool. That pool\n // bypasses be-sdk's createConnectionPool, so this env fallback is what makes\n // graph-integration services attributable in pg_stat_activity /\n // pg_stat_statements. Pure diagnostic metadata; only set when unset.\n ensureServiceApplicationName(productName);\n\n // Singleton state\n const state: GraphIntegrationState<TPrismaClient> = {\n graphEmitter: null,\n extendedPrismaClient: null,\n emitterInitialized: false,\n initializationPromise: null,\n };\n\n /**\n * Initialize the graph event emitter\n * Call this once during application startup before using the database\n *\n * If called multiple times, returns the same initialization promise\n *\n * @returns Promise that resolves when initialization is complete\n */\n async function initializeGraphEmitter(): Promise<void> {\n // Return existing promise if initialization is in progress or complete\n if (state.initializationPromise) {\n return state.initializationPromise;\n }\n\n // If already initialized (and promise was cleared), return immediately\n if (state.emitterInitialized) {\n return;\n }\n\n // Create and cache the initialization promise\n state.initializationPromise = (async () => {\n if (!process.env['GRAPH_EVENTS_ENABLED'] || process.env['GRAPH_EVENTS_ENABLED'] !== 'true') {\n logger.info(`[${serviceName}] Graph events disabled`);\n state.emitterInitialized = true;\n return;\n }\n\n try {\n // Ensure NATS_SERVERS is set (fallback to NATS_URL)\n if (!process.env['NATS_SERVERS'] && process.env['NATS_URL']) {\n process.env['NATS_SERVERS'] = process.env['NATS_URL'];\n }\n\n state.graphEmitter = new GraphEventEmitterImpl();\n // Note: GraphEventEmitterImpl auto-connects on first publishEntityEvent() call\n logger.info(`[${serviceName}] Graph event emitter initialized`);\n state.emitterInitialized = true;\n\n // Initialize graph integration with the configuration\n const basePrisma = createPrismaClient();\n\n state.extendedPrismaClient = initializeGraph(basePrisma, graphConfig, {\n productName,\n eventEmitter: state.graphEmitter,\n enabled: true,\n validateRuntime,\n });\n\n logger.info(`[${serviceName}] Graph integration initialized successfully`);\n } catch (error) {\n logger.error(`[${serviceName}] Failed to initialize graph integration:`, error);\n state.graphEmitter = null;\n state.extendedPrismaClient = null;\n state.emitterInitialized = true; // Mark as initialized to prevent retry loops\n }\n })();\n\n return state.initializationPromise;\n }\n\n /**\n * Get the Prisma client with graph integration\n *\n * Returns the extended Prisma client if graph events are enabled,\n * otherwise returns a fresh base client.\n *\n * When autoInit is enabled, triggers initialization on first call\n *\n * @returns Object with the Prisma client\n */\n function db(): { client: TPrismaClient } {\n // Auto-initialize if enabled and not yet initialized\n if (autoInit && !state.emitterInitialized && !state.initializationPromise) {\n logger.warn(\n `[${serviceName}] Graph emitter not initialized before first database access. Auto-initializing now. ` +\n `Consider calling 'await initializeGraphEmitter()' explicitly during server startup for better control.`\n );\n // Start initialization in the background (non-blocking)\n void initializeGraphEmitter();\n }\n\n // If graph events are not enabled or not initialized, create a base client\n if (\n !process.env['GRAPH_EVENTS_ENABLED'] ||\n process.env['GRAPH_EVENTS_ENABLED'] !== 'true' ||\n !state.extendedPrismaClient\n ) {\n const baseClient = createPrismaClient();\n return { client: baseClient };\n }\n\n return { client: state.extendedPrismaClient };\n }\n\n /**\n * Direct Prisma client accessor via Proxy\n *\n * A Proxy-based accessor that provides direct access to Prisma models\n * without needing to call a function.\n *\n * @example\n * ```typescript\n * const tags = await prisma.universalTag.findMany();\n * await prisma.$transaction([...]);\n * await prisma.$queryRaw`SELECT * FROM \"UniversalTag\"`;\n * ```\n */\n const prisma: TPrismaClient = new Proxy({} as TPrismaClient, {\n get(_, prop: string | symbol) {\n const { client } = db();\n const value = client[prop as keyof TPrismaClient];\n // If it's a function, bind it to the client\n if (typeof value === 'function') {\n return (value as (...args: unknown[]) => unknown).bind(client);\n }\n return value;\n },\n });\n\n /**\n * Cleanup function to disconnect clients and close emitters\n * Call this during application shutdown\n */\n async function cleanup(): Promise<void> {\n if (state.graphEmitter) {\n await state.graphEmitter.disconnect();\n logger.info(`[${serviceName}] Graph event emitter disconnected`);\n }\n\n if (state.extendedPrismaClient) {\n await state.extendedPrismaClient.$disconnect();\n state.extendedPrismaClient = null;\n logger.info(`[${serviceName}] Prisma client disconnected`);\n }\n\n state.emitterInitialized = false;\n }\n\n return {\n /**\n * Initialize graph event emitter\n *\n * With autoInit=true (default), this is called automatically on first database access.\n * You can still call it manually for explicit initialization timing.\n *\n * With autoInit=false, you must call this during application startup.\n */\n initializeGraphEmitter,\n\n /**\n * Get Prisma client with graph integration\n * Returns { client: PrismaClient }\n *\n * If autoInit is enabled, triggers initialization on first call.\n */\n db,\n\n /**\n * Direct Prisma client accessor (Proxy-based)\n * Use this for most database operations\n *\n * If autoInit is enabled, initialization happens automatically.\n */\n prisma,\n\n /**\n * Cleanup function for graceful shutdown\n */\n cleanup,\n\n /**\n * Get the raw graph emitter instance (for advanced use cases)\n */\n getGraphEmitter: () => state.graphEmitter,\n\n /**\n * Check if emitter is initialized\n */\n isInitialized: () => state.emitterInitialized,\n };\n}\n\n/**\n * Helper type to extract the return type of createPrismaGraphIntegration\n * Useful for type definitions in consuming services\n */\nexport type PrismaGraphIntegration<TPrismaClient extends PrismaClientBase> = ReturnType<\n typeof createPrismaGraphIntegration<TPrismaClient>\n>;\n","/**\n * Graph Events Helper\n *\n * Provides a configurable helper for publishing graph entity and relationship events.\n * This allows modules to define their entity types and automatically get event publishing\n * for graph synchronization.\n *\n * @module graph/events-helper\n * @category Graph\n *\n * @example\n * ```typescript\n * import { createGraphEventsHelper } from '@burdenoff/be-sdk/graph';\n *\n * // Create a helper for the tags module\n * const graphEvents = createGraphEventsHelper({\n * moduleName: 'module-tags',\n * entities: {\n * vocabulary: {\n * type: 'UniversalTagVocabulary',\n * getOrgId: (data) => data.tenantId as string,\n * getWorkspaceId: (data) => data.workspaceId as string,\n * },\n * tag: {\n * type: 'UniversalTag',\n * getOrgId: (data) => data.tenantId as string,\n * getWorkspaceId: (data) => data.workspaceId as string,\n * onCreated: async (data, publisher) => {\n * // Publish parent relationship if exists\n * if (data.parentId) {\n * await publisher.publishRelationshipCreated({ ... });\n * }\n * },\n * },\n * },\n * });\n *\n * // Use the helper\n * await graphEvents.vocabulary.created(vocabularyData);\n * await graphEvents.tag.updated(tagData);\n * ```\n */\nimport { logger } from '../logger/index.js';\nimport { getGraphEventEmitter, type EntityEventType, type GraphEventEmitter } from '../event-queue/graph-emitter.js';\n\n/**\n * Options for publishing events\n */\nexport interface GraphEventPublishOptions {\n userId?: string;\n correlationId?: string;\n}\n\n/**\n * Relationship data for graph sync\n */\nexport interface GraphRelationshipData {\n from: { id: string; type: string };\n to: { id: string; type: string };\n relationType: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Entity configuration for graph events\n */\nexport interface GraphEntityConfig {\n /** GraphQL/Database entity type name (e.g., 'UniversalTag') */\n type: string;\n /** Extract organization/tenant ID from entity data */\n getOrgId?: (data: Record<string, unknown>) => string | undefined;\n /** Extract workspace ID from entity data */\n getWorkspaceId?: (data: Record<string, unknown>) => string | undefined;\n /** Hook called after entity created event is published */\n onCreated?: (\n data: Record<string, unknown>,\n publisher: GraphEventsPublisher,\n options?: GraphEventPublishOptions\n ) => Promise<void>;\n /** Hook called after entity updated event is published */\n onUpdated?: (\n data: Record<string, unknown>,\n publisher: GraphEventsPublisher,\n options?: GraphEventPublishOptions\n ) => Promise<void>;\n /** Hook called after entity deleted event is published */\n onDeleted?: (\n data: Record<string, unknown>,\n publisher: GraphEventsPublisher,\n options?: GraphEventPublishOptions\n ) => Promise<void>;\n}\n\n/**\n * Configuration for graph events helper\n */\nexport interface GraphEventsHelperConfig {\n /** Module/product name for event context */\n moduleName: string;\n /** Entity configurations keyed by friendly name */\n entities: Record<string, GraphEntityConfig>;\n}\n\n/**\n * Entity event data for graph sync\n */\nexport interface EntityEventData {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n}\n\n/**\n * Graph Events Publisher\n *\n * Singleton service for publishing entity and relationship events\n * to the graph synchronization system.\n */\nexport class GraphEventsPublisher {\n private static instance: GraphEventsPublisher | null = null;\n private productName: string;\n private initialized = false;\n private emitter: GraphEventEmitter | null = null;\n\n constructor(productName: string = 'unknown') {\n this.productName = productName;\n }\n\n /**\n * Get singleton instance\n */\n static getInstance(productName?: string): GraphEventsPublisher {\n if (!GraphEventsPublisher.instance) {\n GraphEventsPublisher.instance = new GraphEventsPublisher(productName);\n }\n return GraphEventsPublisher.instance;\n }\n\n /**\n * Set the product name (useful when using singleton)\n */\n setProductName(name: string): void {\n this.productName = name;\n }\n\n /**\n * Initialize the publisher\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n try {\n this.emitter = getGraphEventEmitter();\n logger.info('[GraphEventsPublisher] Graph event emitter initialized');\n this.initialized = true;\n\n const natsUrl = process.env['NATS_URL'] || process.env['NATS_SERVERS'];\n if (natsUrl) {\n logger.info(`[GraphEventsPublisher] NATS configured: ${natsUrl}`);\n } else {\n logger.warn('[GraphEventsPublisher] NATS not configured, using in-memory fallback');\n }\n } catch (error) {\n logger.error('[GraphEventsPublisher] Failed to initialize:', error);\n }\n }\n\n /**\n * Ensure initialized before publishing\n */\n private async ensureInitialized(): Promise<void> {\n if (!this.initialized) {\n await this.initialize();\n }\n }\n\n /**\n * Publish entity created event\n */\n async publishEntityCreated(entity: EntityEventData, options?: GraphEventPublishOptions): Promise<void> {\n await this.publishEntityEvent('entity.created', entity, options);\n }\n\n /**\n * Publish entity updated event\n */\n async publishEntityUpdated(entity: EntityEventData, options?: GraphEventPublishOptions): Promise<void> {\n await this.publishEntityEvent('entity.updated', entity, options);\n }\n\n /**\n * Publish entity deleted event\n */\n async publishEntityDeleted(entity: EntityEventData, options?: GraphEventPublishOptions): Promise<void> {\n await this.publishEntityEvent('entity.deleted', entity, options);\n }\n\n /**\n * Publish relationship created event\n */\n async publishRelationshipCreated(\n relationship: GraphRelationshipData,\n organizationId: string,\n options?: GraphEventPublishOptions\n ): Promise<void> {\n await this.publishRelationshipEvent('relationship.created', relationship, organizationId, options);\n }\n\n /**\n * Publish relationship deleted event\n */\n async publishRelationshipDeleted(\n relationship: GraphRelationshipData,\n organizationId: string,\n options?: GraphEventPublishOptions\n ): Promise<void> {\n await this.publishRelationshipEvent('relationship.deleted', relationship, organizationId, options);\n }\n\n /**\n * Internal method to publish entity events\n */\n private async publishEntityEvent(\n eventType: EntityEventType,\n entity: EntityEventData,\n options?: GraphEventPublishOptions\n ): Promise<void> {\n await this.ensureInitialized();\n\n if (!this.emitter) {\n logger.warn('[GraphEventsPublisher] Emitter not initialized, skipping event');\n return;\n }\n\n try {\n await this.emitter.publishEntityEvent(\n eventType,\n {\n id: entity.id,\n type: entity.type,\n data: entity.data,\n },\n {\n productName: this.productName,\n organizationId: entity.organizationId || 'unknown',\n workspaceId: entity.workspaceId,\n actorId: options?.userId,\n }\n );\n\n logger.debug(`[GraphEventsPublisher] Published ${eventType} for ${entity.type}:${entity.id}`);\n } catch (error) {\n logger.error(`[GraphEventsPublisher] Failed to publish ${eventType} for ${entity.type}:${entity.id}:`, error);\n }\n }\n\n /**\n * Internal method to publish relationship events\n */\n private async publishRelationshipEvent(\n eventType: 'relationship.created' | 'relationship.deleted',\n relationship: GraphRelationshipData,\n organizationId: string,\n options?: GraphEventPublishOptions\n ): Promise<void> {\n await this.ensureInitialized();\n\n if (!this.emitter) {\n logger.warn('[GraphEventsPublisher] Emitter not initialized, skipping event');\n return;\n }\n\n try {\n await this.emitter.publishEntityEvent(\n eventType as EntityEventType,\n {\n id: `${relationship.from.id}_${relationship.to.id}`,\n type: relationship.relationType,\n data: {\n from: relationship.from,\n to: relationship.to,\n metadata: relationship.metadata,\n },\n },\n {\n productName: this.productName,\n organizationId,\n actorId: options?.userId,\n }\n );\n\n logger.debug(`[GraphEventsPublisher] Published ${eventType} for ${relationship.relationType}`);\n } catch (error) {\n logger.error(`[GraphEventsPublisher] Failed to publish ${eventType} for ${relationship.relationType}:`, error);\n }\n }\n\n /**\n * Shutdown the publisher\n */\n async shutdown(): Promise<void> {\n this.initialized = false;\n this.emitter = null;\n logger.info('[GraphEventsPublisher] Shutdown complete');\n }\n\n /**\n * Reset singleton (for testing)\n */\n static reset(): void {\n GraphEventsPublisher.instance = null;\n }\n}\n\n/**\n * Get singleton GraphEventsPublisher instance\n */\nexport function getGraphEventsPublisher(productName?: string): GraphEventsPublisher {\n return GraphEventsPublisher.getInstance(productName);\n}\n\n/**\n * Entity event handler type\n */\ntype EntityEventHandler = (data: Record<string, unknown>, options?: GraphEventPublishOptions) => Promise<void>;\n\n/**\n * Entity events object type\n */\ninterface EntityEvents {\n created: EntityEventHandler;\n updated: EntityEventHandler;\n deleted: EntityEventHandler;\n}\n\n/**\n * Graph events helper type\n */\nexport type GraphEventsHelper = Record<string, EntityEvents>;\n\n/**\n * Create a graph events helper with configured entity types\n */\nexport function createGraphEventsHelper(config: GraphEventsHelperConfig): GraphEventsHelper {\n const publisher = new GraphEventsPublisher(config.moduleName);\n const helper: GraphEventsHelper = {};\n\n for (const [name, entityConfig] of Object.entries(config.entities)) {\n helper[name] = {\n created: async (data: Record<string, unknown>, options?: GraphEventPublishOptions): Promise<void> => {\n await publisher.publishEntityCreated(\n {\n id: data['id'] as string,\n type: entityConfig.type,\n data,\n organizationId: entityConfig.getOrgId?.(data),\n workspaceId: entityConfig.getWorkspaceId?.(data),\n },\n options\n );\n\n // Call hook if defined\n if (entityConfig.onCreated) {\n await entityConfig.onCreated(data, publisher, options);\n }\n },\n updated: async (data: Record<string, unknown>, options?: GraphEventPublishOptions): Promise<void> => {\n await publisher.publishEntityUpdated(\n {\n id: data['id'] as string,\n type: entityConfig.type,\n data,\n organizationId: entityConfig.getOrgId?.(data),\n workspaceId: entityConfig.getWorkspaceId?.(data),\n },\n options\n );\n\n if (entityConfig.onUpdated) {\n await entityConfig.onUpdated(data, publisher, options);\n }\n },\n deleted: async (data: Record<string, unknown>, options?: GraphEventPublishOptions): Promise<void> => {\n await publisher.publishEntityDeleted(\n {\n id: data['id'] as string,\n type: entityConfig.type,\n data,\n organizationId: entityConfig.getOrgId?.(data),\n workspaceId: entityConfig.getWorkspaceId?.(data),\n },\n options\n );\n\n if (entityConfig.onDeleted) {\n await entityConfig.onDeleted(data, publisher, options);\n }\n },\n };\n }\n\n return helper;\n}\n","/**\n * Graph Export Service\n *\n * Provides a configurable service for exporting entities and relationships\n * to be consumed by the graph module for synchronization.\n *\n * @module graph/export-service\n * @category Graph\n *\n * @example\n * ```typescript\n * import { createGraphExportService } from '@burdenoff/be-sdk/graph';\n *\n * const exportService = createGraphExportService({\n * moduleName: 'module-tags',\n * config: tagsGraphConfig,\n * fetchers: {\n * UniversalTag: async (workspaceId) => db.universalTag.findMany({ where: { workspaceId } }),\n * UniversalTagVocabulary: async (workspaceId) => db.universalTagVocabulary.findMany({ where: { workspaceId } }),\n * },\n * relationshipFetchers: {\n * tagHierarchy: async (workspaceId) => fetchTagHierarchyRelationships(workspaceId),\n * },\n * });\n *\n * // Export all data\n * const result = await exportService.exportAll(organizationId, workspaceId);\n *\n * // Export only entities\n * const entities = await exportService.exportEntities(organizationId, workspaceId);\n * ```\n */\nimport { logger } from '../logger/index.js';\nimport type { ModuleGraphConfig, RelationshipGraphConfig } from './types.js';\n\n/**\n * Entity data structure for graph export\n */\nexport interface GraphEntityExport {\n /** Entity ID */\n id: string;\n /** Entity type */\n type: string;\n /** Entity data */\n data: Record<string, unknown>;\n /** Organization/Tenant ID */\n organizationId?: string;\n /** Workspace ID */\n workspaceId?: string;\n /** Creation timestamp */\n createdAt: string;\n /** Last update timestamp */\n updatedAt: string;\n}\n\n/**\n * Relationship data structure for graph export\n */\nexport interface GraphRelationshipExport {\n /** Relationship ID */\n id: string;\n /** Relationship type */\n type: string;\n /** Source entity ID */\n fromId: string;\n /** Source entity type */\n fromType: string;\n /** Target entity ID */\n toId: string;\n /** Target entity type */\n toType: string;\n /** Relationship metadata */\n metadata: Record<string, unknown>;\n /** Creation timestamp */\n createdAt: string;\n /** Last update timestamp */\n updatedAt: string;\n}\n\n/**\n * Complete graph export response\n */\nexport interface GraphExportResponse {\n /** Module name */\n moduleName: string;\n /** Product source identifier */\n productSource: string;\n /** Export timestamp */\n exportedAt: string;\n /** Schema information */\n schema: {\n entities: Record<string, { fields: string[]; collection: string }>;\n relationships: Record<\n string,\n {\n from: string;\n fromType: string;\n to: string;\n toType: string;\n edgeType: string;\n }\n >;\n };\n /** Exported data */\n data: {\n entities: Record<string, GraphEntityExport[]>;\n relationships: GraphRelationshipExport[];\n };\n /** Export statistics */\n stats: {\n totalEntities: number;\n totalRelationships: number;\n entityCounts: Record<string, number>;\n };\n}\n\n/**\n * Entity fetcher function type\n */\nexport type EntityFetcher<T = Record<string, unknown>> = (\n organizationId?: string,\n workspaceId?: string\n) => Promise<T[]>;\n\n/**\n * Relationship fetcher function type\n */\nexport type RelationshipFetcher = (organizationId?: string, workspaceId?: string) => Promise<GraphRelationshipExport[]>;\n\n/**\n * Configuration for graph export service\n */\nexport interface GraphExportServiceConfig {\n /** Module name */\n moduleName: string;\n /** Graph configuration */\n config: ModuleGraphConfig;\n /** Entity fetcher functions keyed by entity type */\n fetchers: Record<string, EntityFetcher>;\n /** Relationship fetcher functions */\n relationshipFetchers?: Record<string, RelationshipFetcher>;\n /** Custom entity transformer */\n transformEntity?: (type: string, item: Record<string, unknown>) => GraphEntityExport;\n}\n\n/**\n * Graph Export Service\n *\n * Handles exporting entity and relationship data for graph synchronization.\n */\nexport class GraphExportService {\n private readonly moduleName: string;\n private readonly config: ModuleGraphConfig;\n private readonly fetchers: Record<string, EntityFetcher>;\n private readonly relationshipFetchers: Record<string, RelationshipFetcher>;\n private readonly customTransformer?: (type: string, item: Record<string, unknown>) => GraphEntityExport;\n\n constructor(serviceConfig: GraphExportServiceConfig) {\n this.moduleName = serviceConfig.moduleName;\n this.config = serviceConfig.config;\n this.fetchers = serviceConfig.fetchers;\n this.relationshipFetchers = serviceConfig.relationshipFetchers || {};\n this.customTransformer = serviceConfig.transformEntity;\n }\n\n /**\n * Get the graph configuration schema\n */\n getSchema(): {\n moduleName: string;\n entities: Record<string, { fields: string[]; collection: string }>;\n relationships: Record<\n string,\n {\n from: string;\n fromType: string;\n to: string;\n toType: string;\n edgeType: string;\n }\n >;\n } {\n const entities: Record<string, { fields: string[]; collection: string }> = {};\n const relationships: Record<\n string,\n {\n from: string;\n fromType: string;\n to: string;\n toType: string;\n edgeType: string;\n }\n > = {};\n\n // Transform entity config\n for (const [entityType, config] of Object.entries(this.config.entities)) {\n entities[entityType] = {\n fields: Array.isArray(config.fields) ? config.fields : ['id', 'createdAt', 'updatedAt'],\n collection: config.collection || 'product_entities',\n };\n }\n\n // Transform relationship config\n if (this.config.relationships) {\n for (const [relType, config] of Object.entries(this.config.relationships)) {\n relationships[relType] = {\n from: config.from,\n fromType: config.from,\n to: config.to,\n toType: config.to,\n edgeType: config.label || 'relates_to',\n };\n }\n }\n\n return {\n moduleName: this.config.moduleName,\n entities,\n relationships,\n };\n }\n\n /**\n * Export all entities for a given organization/workspace\n */\n async exportEntities(\n organizationId?: string,\n workspaceId?: string,\n entityTypes?: string[]\n ): Promise<Record<string, GraphEntityExport[]>> {\n const result: Record<string, GraphEntityExport[]> = {};\n const typesToExport = entityTypes || Object.keys(this.config.entities);\n\n for (const entityType of typesToExport) {\n if (!this.config.entities[entityType]) {\n continue;\n }\n\n const fetcher = this.fetchers[entityType];\n if (!fetcher) {\n logger.warn(`[GraphExportService] No fetcher for ${entityType}`);\n result[entityType] = [];\n continue;\n }\n\n try {\n const entities = await fetcher(organizationId, workspaceId);\n result[entityType] = entities.map((item) => this.transformEntity(entityType, item));\n } catch (error) {\n logger.error(`[GraphExportService] Error fetching ${entityType}:`, error);\n result[entityType] = [];\n }\n }\n\n return result;\n }\n\n /**\n * Export all relationships for a given organization/workspace\n */\n async exportRelationships(organizationId?: string, workspaceId?: string): Promise<GraphRelationshipExport[]> {\n const relationships: GraphRelationshipExport[] = [];\n\n for (const [name, fetcher] of Object.entries(this.relationshipFetchers)) {\n try {\n const rels = await fetcher(organizationId, workspaceId);\n relationships.push(...rels);\n } catch (error) {\n logger.error(`[GraphExportService] Error fetching relationships ${name}:`, error);\n }\n }\n\n return relationships;\n }\n\n /**\n * Export complete graph data (schema + entities + relationships)\n */\n async exportAll(organizationId?: string, workspaceId?: string): Promise<GraphExportResponse> {\n const schema = this.getSchema();\n const entities = await this.exportEntities(organizationId, workspaceId);\n const relationships = await this.exportRelationships(organizationId, workspaceId);\n\n // Calculate stats\n const entityCounts: Record<string, number> = {};\n let totalEntities = 0;\n\n for (const [type, items] of Object.entries(entities)) {\n entityCounts[type] = items.length;\n totalEntities += items.length;\n }\n\n return {\n moduleName: this.config.moduleName,\n productSource: this.moduleName,\n exportedAt: new Date().toISOString(),\n schema: {\n entities: schema.entities,\n relationships: schema.relationships,\n },\n data: {\n entities,\n relationships,\n },\n stats: {\n totalEntities,\n totalRelationships: relationships.length,\n entityCounts,\n },\n };\n }\n\n /**\n * Transform a database entity to graph export format\n */\n private transformEntity(type: string, item: Record<string, unknown>): GraphEntityExport {\n if (this.customTransformer) {\n return this.customTransformer(type, item);\n }\n\n const { id, createdAt, updatedAt, workspaceId, tenantId, ...data } = item as {\n id: string;\n createdAt: Date | string;\n updatedAt: Date | string;\n workspaceId?: string;\n tenantId?: string;\n [key: string]: unknown;\n };\n\n return {\n id,\n type,\n data,\n organizationId: tenantId,\n workspaceId,\n createdAt: createdAt instanceof Date ? createdAt.toISOString() : String(createdAt),\n updatedAt: updatedAt instanceof Date ? updatedAt.toISOString() : String(updatedAt),\n };\n }\n}\n\n/**\n * Create a graph export service instance\n */\nexport function createGraphExportService(config: GraphExportServiceConfig): GraphExportService {\n return new GraphExportService(config);\n}\n\n/**\n * Helper function to create a relationship from entity data\n */\nexport function createRelationshipFromEntity(\n entity: Record<string, unknown>,\n relationConfig: RelationshipGraphConfig,\n relationType: string\n): GraphRelationshipExport | null {\n const fromId = entity[relationConfig.from] as string | undefined;\n const toId = entity[relationConfig.to] as string | undefined;\n\n if (!fromId || !toId) {\n return null;\n }\n\n const metadata = relationConfig.extractMetadata ? relationConfig.extractMetadata(entity) : {};\n\n return {\n id: `${relationType}_${entity['id'] || fromId}_${toId}`,\n type: relationType,\n fromId,\n fromType: relationConfig.from || 'Entity',\n toId,\n toType: relationConfig.to || 'Entity',\n metadata,\n createdAt:\n entity['createdAt'] instanceof Date\n ? entity['createdAt'].toISOString()\n : String(entity['createdAt'] || new Date().toISOString()),\n updatedAt:\n entity['updatedAt'] instanceof Date\n ? entity['updatedAt'].toISOString()\n : String(entity['updatedAt'] || new Date().toISOString()),\n };\n}\n","/**\n * Unified Module Graph Definition\n *\n * Provides a single, simplified configuration for graph integration in microservices.\n * Combines schema definition, event publishing, and data export into one unified API.\n *\n * @module graph/module-graph\n * @category Graph\n *\n * @example\n * ```typescript\n * // In your microservice: src/modules/[module]/graph.ts\n * import { defineModuleGraph } from '@burdenoff/be-sdk/graph';\n * import { getDb } from '@burdenoff/be-sdk/prisma';\n *\n * export const tagsGraph = defineModuleGraph({\n * moduleName: 'module-tags',\n *\n * entities: {\n * vocabulary: {\n * type: 'UniversalTagVocabulary',\n * fields: ['id', 'name', 'description', 'workspaceId'],\n * getOrgId: (data) => data.tenantId,\n * getWorkspaceId: (data) => data.workspaceId,\n * fetch: async (_, workspaceId) =>\n * getDb().client.universalTagVocabulary.findMany({\n * where: { deletedAt: null, ...(workspaceId && { workspaceId }) },\n * }),\n * },\n *\n * tag: {\n * type: 'UniversalTag',\n * fields: ['id', 'name', 'vocabularyId', 'parentId'],\n * getOrgId: (data) => data.tenantId,\n * getWorkspaceId: (data) => data.workspaceId,\n * onCreated: async (data, ctx) => {\n * if (data.parentId) {\n * await ctx.publishRelationship({\n * from: { id: data.id, type: 'UniversalTag' },\n * to: { id: data.parentId, type: 'UniversalTag' },\n * relationType: 'child_of',\n * });\n * }\n * },\n * fetch: async (_, workspaceId) =>\n * getDb().client.universalTag.findMany({\n * where: { deletedAt: null, ...(workspaceId && { workspaceId }) },\n * }),\n * },\n * },\n *\n * relationships: {\n * tagHierarchy: {\n * fromType: 'UniversalTag',\n * toType: 'UniversalTag',\n * edgeType: 'child_of',\n * fetch: async (_, workspaceId) => {\n * const tags = await getDb().client.universalTag.findMany({\n * where: { deletedAt: null, parentId: { not: null }, ...(workspaceId && { workspaceId }) },\n * });\n * return tags.map(t => ({\n * id: `hierarchy_${t.id}`,\n * fromId: t.id,\n * toId: t.parentId!,\n * metadata: { hierarchyPath: t.hierarchyPath },\n * }));\n * },\n * },\n * },\n * });\n *\n * // Usage in providers:\n * await tagsGraph.events.vocabulary.created(data);\n * await tagsGraph.events.tag.updated(data);\n *\n * // Usage in index.ts:\n * await tagsGraph.initialize();\n * const schema = tagsGraph.getSchema();\n * const exportData = await tagsGraph.exportAll(orgId, workspaceId);\n * ```\n */\nimport { logger } from '../logger/index.js';\nimport {\n getGraphEventEmitter,\n type EntityEventType,\n type GraphEventEmitter,\n type EntityEventRbacMetadata,\n} from '../event-queue/graph-emitter.js';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\n/**\n * Options for publishing events\n */\nexport interface GraphEventOptions {\n actorId?: string;\n correlationId?: string;\n organizationId?: string;\n}\n\n/**\n * Relationship data for graph events\n */\nexport interface RelationshipEventData {\n from: { id: string; type: string };\n to: { id: string; type: string };\n relationType: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Context provided to entity event hooks\n */\nexport interface EntityEventContext {\n /** Publish a relationship event */\n publishRelationship: (data: RelationshipEventData, orgId?: string) => Promise<void>;\n /** Publish relationship deleted event */\n deleteRelationship: (data: RelationshipEventData, orgId?: string) => Promise<void>;\n /** Get the organization ID from entity data */\n getOrgId: (data: Record<string, unknown>) => string | undefined;\n /** Get the workspace ID from entity data */\n getWorkspaceId: (data: Record<string, unknown>) => string | undefined;\n}\n\n/**\n * Entity event hook function type\n */\nexport type EntityEventHook = (\n data: Record<string, unknown>,\n ctx: EntityEventContext,\n options?: GraphEventOptions\n) => Promise<void>;\n\n/**\n * Entity fetcher function for export\n */\nexport type EntityFetcher<T = Record<string, unknown>> = (\n organizationId?: string,\n workspaceId?: string\n) => Promise<T[]>;\n\n/**\n * Relationship export data\n */\nexport interface RelationshipExportData {\n id: string;\n fromId: string;\n toId: string;\n metadata?: Record<string, unknown>;\n createdAt?: string;\n updatedAt?: string;\n}\n\n/**\n * Relationship fetcher function for export\n */\nexport type RelationshipFetcher = (organizationId?: string, workspaceId?: string) => Promise<RelationshipExportData[]>;\n\n/**\n * RBAC configuration for an entity in the graph.\n * When provided, entity lifecycle events will include RBAC metadata,\n * enabling the RBAC consumer to automatically create/update/delete resources.\n */\nexport interface EntityRbacConfig {\n /** RBAC resource type name (e.g., 'tag', 'conversation', 'bot') */\n resourceTypeName: string;\n /** Extract human-readable name for the RBAC resource. Falls back to entity title. */\n extractName?: (data: Record<string, unknown>) => string | undefined;\n /** Extract a custom identifier for the RBAC resource. Defaults to entity id. */\n extractIdentifier?: (data: Record<string, unknown>) => string | undefined;\n /** Field name on the entity data whose value is used as parentResourceIdentifier in RBAC */\n parentResourceField?: string;\n /** Whether to create an RBAC resource for this entity (default: true) */\n createResource?: boolean;\n}\n\n/**\n * Entity definition in the unified graph config\n */\nexport interface EntityDefinition<T = Record<string, unknown>> {\n /** GraphQL/Database type name (e.g., 'UniversalTag') */\n type: string;\n\n /** Fields to include in graph schema */\n fields?: string[];\n\n /** graph entity label (defaults to 'entity') */\n collection?: string;\n\n /** Extract organization/tenant ID from entity data */\n getOrgId?: (data: Record<string, unknown>) => string | undefined;\n\n /** Extract workspace ID from entity data */\n getWorkspaceId?: (data: Record<string, unknown>) => string | undefined;\n\n /** Hook called after entity created */\n onCreated?: EntityEventHook;\n\n /** Hook called after entity updated */\n onUpdated?: EntityEventHook;\n\n /** Hook called after entity deleted */\n onDeleted?: EntityEventHook;\n\n /** Fetch entities for export (optional - needed only for export API) */\n fetch?: EntityFetcher<T>;\n\n /**\n * RBAC resource tracking configuration.\n * When provided, entity lifecycle events carry RBAC metadata so the\n * rbac-entity-consumer can automatically create/update/delete RBAC resources\n * in sync with the entity's lifecycle.\n */\n rbac?: EntityRbacConfig;\n}\n\n/**\n * Relationship definition in the unified graph config\n */\nexport interface RelationshipDefinition {\n /** Source entity type */\n fromType: string;\n\n /** Target entity type */\n toType: string;\n\n /** Edge type/collection name (e.g., 'child_of', 'tagged_with') */\n edgeType: string;\n\n /** Extract metadata from relationship record */\n extractMetadata?: (record: Record<string, unknown>) => Record<string, unknown>;\n\n /** Fetch relationships for export (optional - needed only for export API) */\n fetch?: RelationshipFetcher;\n}\n\n/**\n * Configuration for defineModuleGraph\n */\nexport interface ModuleGraphDefinition {\n /** Module name (e.g., 'module-tags') */\n moduleName: string;\n\n /**\n * Product source identifier stored in the graph DB and used for filtering.\n * Defaults to moduleName if not set.\n * Use this to group multiple modules under a single product identifier\n * (e.g., set productSource: 'vibecontrols' on all vibecontrols modules so\n * the frontend can filter with productSources: ['vibecontrols']).\n */\n productSource?: string;\n\n /** Entity definitions keyed by friendly name */\n entities: Record<string, EntityDefinition>;\n\n /** Relationship definitions keyed by name */\n relationships?: Record<string, RelationshipDefinition>;\n}\n\n/**\n * Entity event methods\n */\ninterface EntityEventMethods {\n created: (data: Record<string, unknown>, options?: GraphEventOptions) => Promise<void>;\n updated: (data: Record<string, unknown>, options?: GraphEventOptions) => Promise<void>;\n deleted: (data: Record<string, unknown>, options?: GraphEventOptions) => Promise<void>;\n}\n\n/**\n * Entity export data\n */\ninterface EntityExport {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Relationship export data (full)\n */\ninterface RelationshipExport {\n id: string;\n type: string;\n fromId: string;\n fromType: string;\n toId: string;\n toType: string;\n metadata: Record<string, unknown>;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Graph schema\n */\ninterface GraphSchema {\n moduleName: string;\n entities: Record<string, { fields: string[]; collection: string }>;\n relationships: Record<string, { fromType: string; toType: string; edgeType: string }>;\n}\n\n/**\n * Export response\n */\ninterface ExportResponse {\n moduleName: string;\n productSource: string;\n exportedAt: string;\n schema: GraphSchema;\n data: {\n entities: Record<string, EntityExport[]>;\n relationships: RelationshipExport[];\n };\n stats: {\n totalEntities: number;\n totalRelationships: number;\n entityCounts: Record<string, number>;\n };\n}\n\n/**\n * The unified module graph instance\n */\nexport interface ModuleGraph {\n /** Module name */\n readonly moduleName: string;\n\n /** Entity event helpers */\n readonly events: Record<string, EntityEventMethods>;\n\n /** Initialize the graph (call on startup) */\n initialize(): Promise<void>;\n\n /** Shutdown the graph (call on exit) */\n shutdown(): Promise<void>;\n\n /** Get the graph schema */\n getSchema(): GraphSchema;\n\n /** Export all entities */\n exportEntities(\n organizationId?: string,\n workspaceId?: string,\n entityTypes?: string[]\n ): Promise<Record<string, EntityExport[]>>;\n\n /** Export all relationships */\n exportRelationships(organizationId?: string, workspaceId?: string): Promise<RelationshipExport[]>;\n\n /** Export everything (schema + entities + relationships) */\n exportAll(organizationId?: string, workspaceId?: string): Promise<ExportResponse>;\n\n /** Get the raw graph events publisher (for advanced use) */\n getPublisher(): GraphEventsPublisherInternal;\n}\n\n// =============================================================================\n// INTERNAL PUBLISHER\n// =============================================================================\n\n/**\n * Internal graph events publisher\n */\nclass GraphEventsPublisherInternal {\n private productName: string;\n private initialized = false;\n private emitter: GraphEventEmitter | null = null;\n\n constructor(productName: string) {\n this.productName = productName;\n }\n\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n try {\n this.emitter = getGraphEventEmitter();\n logger.info(`[ModuleGraph:${this.productName}] Graph event emitter initialized`);\n this.initialized = true;\n\n const natsUrl = process.env['NATS_URL'] || process.env['NATS_SERVERS'];\n if (natsUrl) {\n logger.info(`[ModuleGraph:${this.productName}] NATS configured: ${natsUrl}`);\n } else {\n logger.warn(`[ModuleGraph:${this.productName}] NATS not configured, using in-memory fallback`);\n }\n } catch (error) {\n logger.error(`[ModuleGraph:${this.productName}] Failed to initialize:`, error);\n }\n }\n\n private async ensureInitialized(): Promise<void> {\n if (!this.initialized) {\n await this.initialize();\n }\n }\n\n async publishEntityCreated(\n entity: {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n },\n options?: GraphEventOptions,\n rbac?: EntityEventRbacMetadata\n ): Promise<void> {\n await this.publishEntityEvent('entity.created', entity, options, rbac);\n }\n\n async publishEntityUpdated(\n entity: {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n },\n options?: GraphEventOptions,\n rbac?: EntityEventRbacMetadata\n ): Promise<void> {\n await this.publishEntityEvent('entity.updated', entity, options, rbac);\n }\n\n async publishEntityDeleted(\n entity: {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n },\n options?: GraphEventOptions,\n rbac?: EntityEventRbacMetadata\n ): Promise<void> {\n await this.publishEntityEvent('entity.deleted', entity, options, rbac);\n }\n\n async publishRelationshipCreated(\n relationship: RelationshipEventData,\n organizationId: string,\n options?: GraphEventOptions\n ): Promise<void> {\n await this.publishRelationshipEvent('relationship.created', relationship, organizationId, options);\n }\n\n async publishRelationshipDeleted(\n relationship: RelationshipEventData,\n organizationId: string,\n options?: GraphEventOptions\n ): Promise<void> {\n await this.publishRelationshipEvent('relationship.deleted', relationship, organizationId, options);\n }\n\n private async publishEntityEvent(\n eventType: EntityEventType,\n entity: {\n id: string;\n type: string;\n data: Record<string, unknown>;\n organizationId?: string;\n workspaceId?: string;\n },\n options?: GraphEventOptions,\n rbac?: EntityEventRbacMetadata\n ): Promise<void> {\n await this.ensureInitialized();\n\n if (!this.emitter) {\n logger.warn(`[ModuleGraph:${this.productName}] Emitter not initialized, skipping event`);\n return;\n }\n\n try {\n await this.emitter.publishEntityEvent(\n eventType,\n {\n id: entity.id,\n type: entity.type,\n data: entity.data,\n },\n {\n productName: this.productName,\n organizationId: options?.organizationId ?? entity.organizationId ?? 'unknown',\n workspaceId: entity.workspaceId,\n actorId: options?.actorId,\n },\n rbac\n );\n\n logger.debug(`[ModuleGraph:${this.productName}] Published ${eventType} for ${entity.type}:${entity.id}`, {\n hasRbac: !!rbac,\n });\n } catch (error) {\n logger.error(`[ModuleGraph:${this.productName}] Failed to publish ${eventType}:`, error);\n }\n }\n\n private async publishRelationshipEvent(\n eventType: 'relationship.created' | 'relationship.deleted',\n relationship: RelationshipEventData,\n organizationId: string,\n options?: GraphEventOptions\n ): Promise<void> {\n await this.ensureInitialized();\n\n if (!this.emitter) {\n logger.warn(`[ModuleGraph:${this.productName}] Emitter not initialized, skipping event`);\n return;\n }\n\n try {\n await this.emitter.publishEntityEvent(\n eventType as EntityEventType,\n {\n id: `${relationship.from.id}_${relationship.to.id}`,\n type: relationship.relationType,\n data: {\n from: relationship.from,\n to: relationship.to,\n metadata: relationship.metadata,\n },\n },\n {\n productName: this.productName,\n organizationId,\n actorId: options?.actorId,\n }\n );\n\n logger.debug(`[ModuleGraph:${this.productName}] Published ${eventType} for ${relationship.relationType}`);\n } catch (error) {\n logger.error(`[ModuleGraph:${this.productName}] Failed to publish ${eventType}:`, error);\n }\n }\n\n async shutdown(): Promise<void> {\n this.initialized = false;\n this.emitter = null;\n logger.info(`[ModuleGraph:${this.productName}] Shutdown complete`);\n }\n}\n\n// =============================================================================\n// FACTORY FUNCTION\n// =============================================================================\n\n/**\n * Define a module graph configuration\n *\n * This is the main entry point for configuring graph integration in a microservice.\n * It provides a unified API for schema definition, event publishing, and data export.\n *\n * @param definition - The module graph definition\n * @returns A ModuleGraph instance with all graph functionality\n *\n * @example\n * ```typescript\n * export const myGraph = defineModuleGraph({\n * moduleName: 'module-tags',\n * entities: {\n * tag: {\n * type: 'UniversalTag',\n * fields: ['id', 'name'],\n * getOrgId: (d) => d.tenantId as string,\n * fetch: async () => db.tag.findMany(),\n * },\n * },\n * });\n *\n * // In providers:\n * await myGraph.events.tag.created(tagData);\n *\n * // In index.ts:\n * await myGraph.initialize();\n * ```\n */\nexport function defineModuleGraph(definition: ModuleGraphDefinition): ModuleGraph {\n const { moduleName, productSource, entities, relationships = {} } = definition;\n const publisher = new GraphEventsPublisherInternal(productSource ?? moduleName);\n\n // Build entity event methods\n const events: Record<string, EntityEventMethods> = {};\n\n for (const [entityName, entityDef] of Object.entries(entities)) {\n const getOrgId = entityDef.getOrgId || ((): string | undefined => undefined);\n const getWorkspaceId = entityDef.getWorkspaceId || ((): string | undefined => undefined);\n\n // Create event context for hooks\n const createEventContext = (): EntityEventContext => ({\n publishRelationship: async (data: RelationshipEventData, orgId?: string): Promise<void> => {\n await publisher.publishRelationshipCreated(data, orgId || 'unknown');\n },\n deleteRelationship: async (data: RelationshipEventData, orgId?: string): Promise<void> => {\n await publisher.publishRelationshipDeleted(data, orgId || 'unknown');\n },\n getOrgId,\n getWorkspaceId,\n });\n\n // Build RBAC metadata extractor from entity config\n const buildRbacMetadata = (data: Record<string, unknown>): EntityEventRbacMetadata | undefined => {\n if (!entityDef.rbac) return undefined;\n const rbacConfig = entityDef.rbac;\n if (rbacConfig.createResource === false) return undefined;\n\n const entityId = data['id'] as string;\n const title = (data['name'] as string) || (data['title'] as string) || (data['label'] as string) || entityId;\n\n return {\n resourceTypeName: rbacConfig.resourceTypeName,\n name: rbacConfig.extractName?.(data) ?? title,\n identifier: rbacConfig.extractIdentifier?.(data) ?? entityId,\n parentResourceIdentifier: rbacConfig.parentResourceField\n ? (data[rbacConfig.parentResourceField] as string | undefined)\n : undefined,\n createResource: rbacConfig.createResource ?? true,\n };\n };\n\n events[entityName] = {\n created: async (data: Record<string, unknown>, options?: GraphEventOptions): Promise<void> => {\n await publisher.publishEntityCreated(\n {\n id: data['id'] as string,\n type: entityDef.type,\n data,\n organizationId: getOrgId(data),\n workspaceId: getWorkspaceId(data),\n },\n options,\n buildRbacMetadata(data)\n );\n\n if (entityDef.onCreated) {\n await entityDef.onCreated(data, createEventContext(), options);\n }\n },\n\n updated: async (data: Record<string, unknown>, options?: GraphEventOptions): Promise<void> => {\n await publisher.publishEntityUpdated(\n {\n id: data['id'] as string,\n type: entityDef.type,\n data,\n organizationId: getOrgId(data),\n workspaceId: getWorkspaceId(data),\n },\n options,\n buildRbacMetadata(data)\n );\n\n if (entityDef.onUpdated) {\n await entityDef.onUpdated(data, createEventContext(), options);\n }\n },\n\n deleted: async (data: Record<string, unknown>, options?: GraphEventOptions): Promise<void> => {\n await publisher.publishEntityDeleted(\n {\n id: data['id'] as string,\n type: entityDef.type,\n data,\n organizationId: getOrgId(data),\n workspaceId: getWorkspaceId(data),\n },\n options,\n buildRbacMetadata(data)\n );\n\n if (entityDef.onDeleted) {\n await entityDef.onDeleted(data, createEventContext(), options);\n }\n },\n };\n }\n\n // Build schema\n const getSchema = (): GraphSchema => {\n const entitySchema: Record<string, { fields: string[]; collection: string }> = {};\n const relationshipSchema: Record<string, { fromType: string; toType: string; edgeType: string }> = {};\n\n for (const [, entityDef] of Object.entries(entities)) {\n entitySchema[entityDef.type] = {\n fields: entityDef.fields || ['id', 'createdAt', 'updatedAt'],\n collection: entityDef.collection || 'entity',\n };\n }\n\n for (const [relName, relDef] of Object.entries(relationships)) {\n relationshipSchema[relName] = {\n fromType: relDef.fromType,\n toType: relDef.toType,\n edgeType: relDef.edgeType,\n };\n }\n\n return { moduleName, entities: entitySchema, relationships: relationshipSchema };\n };\n\n // Export entities\n const exportEntities = async (\n organizationId?: string,\n workspaceId?: string,\n entityTypes?: string[]\n ): Promise<Record<string, EntityExport[]>> => {\n const result: Record<string, EntityExport[]> = {};\n\n for (const [entityName, entityDef] of Object.entries(entities)) {\n if (entityTypes && !entityTypes.includes(entityDef.type)) {\n continue;\n }\n\n if (!entityDef.fetch) {\n result[entityDef.type] = [];\n continue;\n }\n\n try {\n const items = await entityDef.fetch(organizationId, workspaceId);\n result[entityDef.type] = items.map((item) => {\n const {\n id,\n createdAt,\n updatedAt,\n workspaceId: ws,\n tenantId,\n ...data\n } = item as {\n id: string;\n createdAt: Date | string;\n updatedAt: Date | string;\n workspaceId?: string;\n tenantId?: string;\n [key: string]: unknown;\n };\n\n return {\n id,\n type: entityDef.type,\n data,\n organizationId: tenantId,\n workspaceId: ws,\n createdAt: createdAt instanceof Date ? createdAt.toISOString() : String(createdAt),\n updatedAt: updatedAt instanceof Date ? updatedAt.toISOString() : String(updatedAt),\n };\n });\n } catch (error) {\n logger.error(`[ModuleGraph:${moduleName}] Error fetching ${entityName}:`, error);\n result[entityDef.type] = [];\n }\n }\n\n return result;\n };\n\n // Export relationships\n const exportRelationships = async (organizationId?: string, workspaceId?: string): Promise<RelationshipExport[]> => {\n const result: RelationshipExport[] = [];\n\n for (const [relName, relDef] of Object.entries(relationships)) {\n if (!relDef.fetch) {\n continue;\n }\n\n try {\n const items = await relDef.fetch(organizationId, workspaceId);\n for (const item of items) {\n result.push({\n id: item.id,\n type: relDef.edgeType,\n fromId: item.fromId,\n fromType: relDef.fromType,\n toId: item.toId,\n toType: relDef.toType,\n metadata: item.metadata || {},\n createdAt: item.createdAt || new Date().toISOString(),\n updatedAt: item.updatedAt || new Date().toISOString(),\n });\n }\n } catch (error) {\n logger.error(`[ModuleGraph:${moduleName}] Error fetching relationship ${relName}:`, error);\n }\n }\n\n return result;\n };\n\n // Export all\n const exportAll = async (organizationId?: string, workspaceId?: string): Promise<ExportResponse> => {\n const schema = getSchema();\n const entitiesData = await exportEntities(organizationId, workspaceId);\n const relationshipsData = await exportRelationships(organizationId, workspaceId);\n\n const entityCounts: Record<string, number> = {};\n let totalEntities = 0;\n\n for (const [type, items] of Object.entries(entitiesData)) {\n entityCounts[type] = items.length;\n totalEntities += items.length;\n }\n\n return {\n moduleName,\n productSource: productSource ?? moduleName,\n exportedAt: new Date().toISOString(),\n schema,\n data: {\n entities: entitiesData,\n relationships: relationshipsData,\n },\n stats: {\n totalEntities,\n totalRelationships: relationshipsData.length,\n entityCounts,\n },\n };\n };\n\n return {\n moduleName,\n events,\n initialize: () => publisher.initialize(),\n shutdown: () => publisher.shutdown(),\n getSchema,\n exportEntities,\n exportRelationships,\n exportAll,\n getPublisher: () => publisher,\n };\n}\n\n// =============================================================================\n// RE-EXPORT TYPES FOR CONVENIENCE\n// =============================================================================\n\nexport type {\n EntityExport as GraphEntityExport,\n RelationshipExport as GraphRelationshipExport,\n ExportResponse as GraphExportResponse,\n GraphSchema,\n};\n","/**\n * Graph Configuration Builder\n *\n * Provides the defineGraphConfig() function with full type inference.\n * This is the ONLY function developers use in their microservice.\n *\n * @module graph/config/builder\n * @category Graph\n */\n\nimport type {\n GenericGraphConfig,\n GenericEntityConfig,\n GenericRelationshipConfig,\n GraphValidationResult,\n GraphValidationError,\n FieldMapper,\n} from './types.js';\nimport { logger } from '../../logger/index.js';\nimport { GraphRegistry } from '../utils/registry.js';\nimport type { EntityGraphConfig, RelationshipGraphConfig } from '../types.js';\n\n/**\n * Standard field presets for automatic inclusion\n */\nexport const STANDARD_FIELDS = ['id', 'createdAt', 'updatedAt'] as const;\nexport const SOFT_DELETE_FIELDS = ['deletedAt'] as const;\nexport const AUDIT_FIELDS = ['metadata', 'context'] as const;\nexport const TENANT_FIELDS = ['workspaceId', 'tenantId'] as const;\n\n/**\n * Smart default implementations\n */\n\n/**\n * Default getWorkspaceId - reads workspaceId field directly\n */\nconst DEFAULT_GET_WORKSPACE_ID: FieldMapper<string> = (data) => data['workspaceId'] as string | undefined;\n\n/**\n * Default getOrgId - tries tenantId first, then context.organizationId\n * This handles both direct tenantId fields and context-based organization references\n */\nconst DEFAULT_GET_ORG_ID: FieldMapper<string> = (data) => {\n // Try tenantId first (direct field pattern used in tags service)\n if (data['tenantId']) {\n return data['tenantId'] as string;\n }\n\n // Fallback to context.organizationId (pattern used in vibecontrols)\n const context = data['context'] as Record<string, unknown> | undefined;\n return context?.['organizationId'] as string | undefined;\n};\n\n/**\n * Default extractTitle - generates {entityType}_{id} pattern\n *\n * This provides a consistent, unambiguous title for all entities.\n * For example: workspace_abc123, agent_xyz789, session_def456\n *\n * The entityType is passed in via the entity configuration context.\n */\nfunction createDefaultExtractTitle(entityType: string): FieldMapper<string> {\n return (data) => {\n const id = data['id'];\n if (typeof id === 'string' && id.length > 0) {\n return `${entityType.toLowerCase()}_${id}`;\n }\n return undefined;\n };\n}\n\n/**\n * Generate relationship label from camelCase name to SCREAMING_SNAKE_CASE\n * Example: TagToVocabulary → TAG_TO_VOCABULARY\n */\nfunction generateRelationshipLabel(relationshipName: string): string {\n return relationshipName\n .replace(/([A-Z])/g, '_$1')\n .toUpperCase()\n .replace(/^_/, '');\n}\n\n/**\n * Extract fields from Prisma model, excluding SDK defaults\n *\n * This function auto-extracts scalar fields from a Prisma model using the\n * generated prisma-fields.ts, then applies exclusions and inclusions.\n *\n * @param modelName - Prisma model name (e.g., 'User', 'Project', 'Agent')\n * @param options - Field extraction options\n * @param prismaFieldsModule - Generated Prisma fields module\n * @returns Array of field names for the entity\n */\nfunction extractFieldsFromModel(\n modelName: string,\n options: {\n exclude?: string[];\n include?: string[];\n softDelete?: boolean;\n multiTenant?: boolean;\n audit?: boolean;\n },\n prismaFieldsModule: PrismaFieldsModule\n): string[] {\n // Verify model exists\n if (!prismaFieldsModule.hasModel(modelName)) {\n const availableModels = prismaFieldsModule.getAllModelNames().join(', ');\n throw new Error(`Prisma model '${modelName}' not found. Available models: ${availableModels}`);\n }\n\n // Get all scalar fields from Prisma model\n const allFields = prismaFieldsModule.getScalarFields(modelName);\n\n // Build SDK default fields that will be auto-added (so we exclude them from Prisma extraction)\n const sdkDefaults = [\n ...STANDARD_FIELDS, // id, createdAt, updatedAt\n ...(options.softDelete !== false ? SOFT_DELETE_FIELDS : []), // deletedAt\n ...(options.multiTenant !== false ? TENANT_FIELDS : []), // workspaceId, tenantId\n ...(options.audit !== false ? AUDIT_FIELDS : []), // metadata, context\n ];\n\n // Build exclusion set (SDK defaults + user exclusions)\n const excluded = new Set([...sdkDefaults, ...(options.exclude ?? [])]);\n\n // Filter out excluded fields from Prisma model\n const filteredFields = allFields.filter((field) => !excluded.has(field));\n\n // Add any explicitly included fields\n const finalFields = [...filteredFields, ...(options.include ?? [])];\n\n return finalFields;\n}\n\n/**\n * Extended entity configuration with options for auto-including fields\n */\nexport interface DefineEntityConfigOptions extends Omit<GenericEntityConfig, 'fields'> {\n /**\n * Entity-specific fields (standard fields like id, createdAt, etc. are auto-included)\n *\n * You can either:\n * 1. Manually specify fields: `fields: ['name', 'email', ...]`\n * 2. Use Prisma model name: `model: 'User'` (requires generated prisma-fields.ts)\n * 3. Use model with exclusions: `model: 'User', exclude: ['internalField']`\n *\n * When using `model`, fields are auto-extracted from Prisma schema\n */\n fields?: string[];\n\n /**\n * Prisma model name to auto-extract fields from\n *\n * Requires the burdenoff-prisma-field-generator to be configured in your Prisma schema.\n * When specified, fields are automatically extracted from the generated prisma-fields.ts\n *\n * @example\n * ```typescript\n * // Auto-extract all fields from User model\n * User: {\n * model: 'User',\n * // extractTitle, getOrgId, etc. can still be customized\n * }\n * ```\n */\n model?: string;\n\n /**\n * Fields to exclude when using `model` auto-extraction\n *\n * Useful to exclude internal/computed fields that shouldn't be in the graph\n *\n * @example\n * ```typescript\n * User: {\n * model: 'User',\n * exclude: ['passwordHash', 'internalCounter']\n * }\n * ```\n */\n exclude?: string[];\n\n /**\n * Additional fields to include beyond what's in the Prisma model\n *\n * Useful for computed/virtual fields not in the database\n *\n * @example\n * ```typescript\n * User: {\n * model: 'User',\n * include: ['fullName', 'avatarUrl']\n * }\n * ```\n */\n include?: string[];\n\n /**\n * Auto-include soft delete field (deletedAt)\n * @default true\n */\n softDelete?: boolean;\n\n /**\n * Auto-include multi-tenant fields (workspaceId, tenantId)\n * @default true\n */\n multiTenant?: boolean;\n\n /**\n * Auto-include audit fields (metadata, context)\n * @default true\n */\n audit?: boolean;\n}\n\n/**\n * Extended relationship configuration with optional fields\n */\nexport interface DefineRelationshipConfigOptions extends Omit<GenericRelationshipConfig, 'label' | 'toField'> {\n /**\n * Relationship label - auto-generated from key if not provided\n */\n label?: string;\n\n /**\n * Target field - defaults to 'id' if not provided\n * @default 'id'\n */\n toField?: string;\n}\n\n/**\n * Validate entity configuration\n *\n * Ensures the entity config has all required fields and valid functions.\n */\nfunction validateEntityConfig(entityType: string, config: GenericEntityConfig): GraphValidationError[] {\n const errors: GraphValidationError[] = [];\n\n // Check required fields\n if (!config.fields || config.fields.length === 0) {\n errors.push({\n type: 'INVALID_ENTITY_TYPE',\n entityType,\n message: `Entity '${entityType}' must have at least one field`,\n });\n }\n\n // Check getWorkspaceId is defined\n if (!config.getWorkspaceId) {\n errors.push({\n type: 'MISSING_WORKSPACE_ID',\n entityType,\n message: `Entity '${entityType}' must define getWorkspaceId() to enforce workspace boundary`,\n });\n }\n\n // Check getOrgId is defined\n if (!config.getOrgId) {\n errors.push({\n type: 'MISSING_ORG_ID',\n entityType,\n message: `Entity '${entityType}' must define getOrgId() for multi-tenant isolation`,\n });\n }\n\n return errors;\n}\n\n/**\n * Validate relationship configuration\n */\nfunction validateRelationshipConfig(\n relationshipKey: string,\n config: GenericRelationshipConfig,\n entityTypes: Set<string>\n): GraphValidationError[] {\n const errors: GraphValidationError[] = [];\n\n // Check from entity exists\n if (!entityTypes.has(config.from)) {\n errors.push({\n type: 'INVALID_RELATIONSHIP',\n relationshipKey,\n message: `Relationship '${relationshipKey}' references unknown 'from' entity: ${config.from}`,\n });\n }\n\n // Check to entity exists (unless polymorphic)\n if (config.to !== '*' && !entityTypes.has(config.to)) {\n errors.push({\n type: 'INVALID_RELATIONSHIP',\n relationshipKey,\n message: `Relationship '${relationshipKey}' references unknown 'to' entity: ${config.to}`,\n });\n }\n\n // Check polymorphic relationships have type field\n if (config.to === '*' && !config.polymorphicTypeField) {\n errors.push({\n type: 'INVALID_RELATIONSHIP',\n relationshipKey,\n message: `Polymorphic relationship '${relationshipKey}' must define polymorphicTypeField`,\n });\n }\n\n // Check required fields\n if (!config.fromField) {\n errors.push({\n type: 'INVALID_RELATIONSHIP',\n relationshipKey,\n message: `Relationship '${relationshipKey}' must define fromField`,\n });\n }\n\n if (!config.label) {\n errors.push({\n type: 'INVALID_RELATIONSHIP',\n relationshipKey,\n message: `Relationship '${relationshipKey}' must define label`,\n });\n }\n\n return errors;\n}\n\n/**\n * Validate workspace boundary enforcement\n *\n * This ensures no entity can exist without a workspace connection.\n * Special entities like Workspace and Project can be roots.\n */\nfunction validateWorkspaceBoundary(\n config: GenericGraphConfig,\n _entityTypes: Set<string>\n): { errors: GraphValidationError[]; warnings: string[] } {\n const errors: GraphValidationError[] = [];\n const warnings: string[] = [];\n\n // Track which entities are root-eligible\n const rootTypes = new Set<string>(['Workspace', 'Project', 'Organization', 'Tenant']);\n\n // Check each entity\n for (const [entityType, entityConfig] of Object.entries(config.entities)) {\n if (entityConfig.enabled === false) continue;\n\n // Root types are always valid\n if (rootTypes.has(entityType)) {\n continue;\n }\n\n // Non-root entities MUST have getWorkspaceId defined\n if (!entityConfig.getWorkspaceId) {\n errors.push({\n type: 'ORPHANED_ENTITY',\n entityType,\n message: `Entity '${entityType}' has no workspace boundary - every entity must connect to a workspace`,\n });\n continue;\n }\n\n // Check if entity has a relationship to Workspace or Project\n let hasWorkspaceLink = false;\n if (config.relationships) {\n for (const [, relConfig] of Object.entries(config.relationships)) {\n if (relConfig.enabled === false) continue;\n\n if (\n relConfig.from === entityType &&\n (relConfig.to === 'Workspace' || relConfig.to === 'Project' || rootTypes.has(relConfig.to))\n ) {\n hasWorkspaceLink = true;\n break;\n }\n }\n }\n\n if (!hasWorkspaceLink) {\n warnings.push(\n `Entity '${entityType}' has no direct relationship to Workspace/Project. ` +\n `Ensure getWorkspaceId() is correctly implemented.`\n );\n }\n }\n\n return { errors, warnings };\n}\n\n/**\n * Validate no duplicate entity types\n */\nfunction validateNoDuplicates(\n config: GenericGraphConfig,\n _entityTypes: Set<string>\n): { errors: GraphValidationError[]; warnings: string[] } {\n const errors: GraphValidationError[] = [];\n const warnings: string[] = [];\n\n const seenEntityTypes = new Set<string>();\n const relationshipLabels = new Set<string>();\n\n // Check entity types\n for (const entityType of Object.keys(config.entities)) {\n if (seenEntityTypes.has(entityType)) {\n errors.push({\n type: 'DUPLICATE_ENTITY_TYPE',\n entityType,\n message: `Duplicate entity type: ${entityType}`,\n });\n }\n seenEntityTypes.add(entityType);\n }\n\n // Check relationship labels\n if (config.relationships) {\n for (const [key, relConfig] of Object.entries(config.relationships)) {\n const label = relConfig.label;\n if (relationshipLabels.has(label)) {\n warnings.push(`Duplicate relationship label: ${label} (in ${key}). This may cause query ambiguity.`);\n }\n relationshipLabels.add(label);\n }\n }\n\n return { errors, warnings };\n}\n\n/**\n * Perform full validation of graph configuration\n */\nfunction validateGraphConfig(config: GenericGraphConfig): GraphValidationResult {\n const allErrors: GraphValidationError[] = [];\n const allWarnings: string[] = [];\n\n // Validate entities\n for (const [entityType, entityConfig] of Object.entries(config.entities)) {\n if (entityConfig.enabled === false) continue;\n const errors = validateEntityConfig(entityType, entityConfig);\n allErrors.push(...errors);\n }\n\n // Collect entity types\n const entityTypes = new Set(Object.keys(config.entities));\n\n // Validate relationships\n if (config.relationships) {\n for (const [relationshipKey, relationshipConfig] of Object.entries(config.relationships)) {\n if (relationshipConfig.enabled === false) continue;\n const errors = validateRelationshipConfig(relationshipKey, relationshipConfig, entityTypes);\n allErrors.push(...errors);\n }\n }\n\n // Validate workspace boundary\n const boundaryResult = validateWorkspaceBoundary(config, entityTypes);\n allErrors.push(...boundaryResult.errors);\n allWarnings.push(...boundaryResult.warnings);\n\n // Validate no duplicates\n const duplicateResult = validateNoDuplicates(config, entityTypes);\n allErrors.push(...duplicateResult.errors);\n allWarnings.push(...duplicateResult.warnings);\n\n return {\n valid: allErrors.length === 0,\n errors: allErrors,\n warnings: allWarnings,\n };\n}\n\n/**\n * Prisma fields module interface (from generated prisma-fields.ts)\n */\nexport interface PrismaFieldsModule {\n getScalarFields: (modelName: string) => string[];\n hasModel: (modelName: string) => boolean;\n getAllModelNames: () => string[];\n}\n\n/**\n * Extended configuration options with auto-defaults\n */\nexport interface DefineGraphConfigOptions {\n /**\n * Module name for logging and identification\n */\n moduleName: string;\n\n /**\n * Entity configurations with extended options\n */\n entities: Record<string, DefineEntityConfigOptions>;\n\n /**\n * Relationship configurations with optional fields\n */\n relationships?: Record<string, DefineRelationshipConfigOptions>;\n\n /**\n * Optional Prisma fields module for auto-extraction\n *\n * Import from your generated prisma-fields.ts to enable model-based field extraction:\n *\n * @example\n * ```typescript\n * import * as prismaFields from './generated/prisma-fields.js';\n * import { defineGraphConfig } from '@burdenoff/be-sdk/graph';\n *\n * export const graphConfig = defineGraphConfig({\n * moduleName: 'module-users',\n * prismaFieldsModule: prismaFields,\n * entities: {\n * User: {\n * model: 'User', // Auto-extract fields from Prisma model\n * exclude: ['passwordHash'],\n * },\n * },\n * });\n * ```\n */\n prismaFieldsModule?: PrismaFieldsModule;\n}\n\n/**\n * Define graph configuration for a microservice\n *\n * This is the ONLY function developers need to call in their microservice.\n * It provides full type inference, validation, and intelligent defaults.\n *\n * **Automatic Defaults Applied**:\n * - **Collection**: Defaults to 'entities' for all entities\n * - **Standard Fields**: Auto-includes id, createdAt, updatedAt\n * - **Soft Delete**: Auto-includes deletedAt (disable with `softDelete: false`)\n * - **Multi-Tenant**: Auto-includes workspaceId, tenantId (disable with `multiTenant: false`)\n * - **Audit**: Auto-includes metadata, context (disable with `audit: false`)\n * - **getWorkspaceId**: Reads data['workspaceId'] (can override)\n * - **getOrgId**: Tries data['tenantId'], then data['context']['organizationId'] (can override)\n * - **extractTitle**: Generates {entityType}_{id} pattern (e.g., user_abc123) (can override)\n * - **toField**: Defaults to 'id' for relationships (can override)\n * - **label**: Auto-generates from relationship name (e.g., UserToProject → USER_TO_PROJECT)\n * - **multiTenant: false**: Automatically sets getWorkspaceId/getOrgId to return undefined\n *\n * @param config - The graph configuration with extended options\n * @returns Fully resolved configuration with all defaults applied\n *\n * @example\n * ```typescript\n * // BEFORE - Old approach with explicit everything\n * export const graphConfig = defineGraphConfig({\n * moduleName: 'module-users',\n * entities: {\n * User: {\n * collection: 'entities',\n * fields: ['id', 'email', 'name', 'workspaceId', 'tenantId', 'context', 'createdAt', 'updatedAt'],\n * getWorkspaceId: (data) => data.workspaceId as string,\n * getOrgId: (data) => data.tenantId as string,\n * extractTitle: (data) => data.name as string,\n * },\n * },\n * relationships: {\n * UserToProject: {\n * from: 'User',\n * to: 'Project',\n * fromField: 'projectId',\n * toField: 'id',\n * label: 'BELONGS_TO_PROJECT',\n * },\n * },\n * });\n *\n * // AFTER - New approach with intelligent defaults + model extraction\n * export const graphConfig = defineGraphConfig({\n * moduleName: 'module-users',\n * prismaFieldsModule: prismaFields, // Enable model-based extraction\n * entities: {\n * User: {\n * model: 'User', // Auto-extracts all fields from Prisma model\n * // All defaults auto-applied:\n * // - collection: 'entities'\n * // - Standard fields: id, createdAt, updatedAt\n * // - Multi-tenant: workspaceId, tenantId\n * // - Audit: metadata, context\n * // - getWorkspaceId: reads workspaceId\n * // - getOrgId: tries tenantId, then context.organizationId\n * // - extractTitle: generates user_{id} pattern\n * },\n * },\n * relationships: {\n * UserToProject: {\n * from: 'User',\n * to: 'Project',\n * fromField: 'projectId',\n * description: 'User belongs to a project',\n * // Auto-defaults:\n * // - toField: 'id'\n * // - label: 'USER_TO_PROJECT' (generated from key name)\n * },\n * },\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Custom overrides when needed\n * export const graphConfig = defineGraphConfig({\n * moduleName: 'module-projects',\n * prismaFieldsModule: prismaFields,\n * entities: {\n * ProjectRelation: {\n * model: 'ProjectRelation',\n * multiTenant: false, // Auto-sets getWorkspaceId/getOrgId to undefined\n * extractTitle: (data) => `Relation: ${data.type}`, // Custom title\n * },\n * },\n * relationships: {\n * ProjectHierarchy: {\n * from: 'Project',\n * to: 'Project',\n * fromField: 'parentId',\n * label: 'HAS_PARENT', // Override auto-generated 'PROJECT_HIERARCHY'\n * extractMetadata: (data) => ({ depth: data.depth }),\n * },\n * },\n * });\n * ```\n */\n/**\n * Process a single entity configuration with smart defaults\n */\nfunction processEntityConfig(\n entityName: string,\n entityOptions: DefineEntityConfigOptions,\n prismaFieldsModule: PrismaFieldsModule | undefined\n): GenericEntityConfig {\n const {\n softDelete = true,\n multiTenant = true,\n audit = true,\n fields,\n model,\n exclude,\n include,\n collection,\n getWorkspaceId,\n getOrgId,\n extractTitle,\n rbac,\n ...rest\n } = entityOptions;\n\n // Determine entity-specific fields (either from model or manual)\n let entityFields: string[];\n\n if (model) {\n // Auto-extract from Prisma model\n if (!prismaFieldsModule) {\n throw new Error(\n `Entity '${entityName}' uses model='${model}' but prismaFieldsModule is not provided. ` +\n `Import prisma-fields.ts and pass it to defineGraphConfig({ prismaFieldsModule: ... })`\n );\n }\n\n entityFields = extractFieldsFromModel(\n model,\n { exclude, include, softDelete, multiTenant, audit },\n prismaFieldsModule\n );\n } else if (fields) {\n // Manual field specification\n entityFields = fields;\n } else {\n throw new Error(`Entity '${entityName}' must specify either 'fields' or 'model' for field definition`);\n }\n\n // Build auto-included SDK default fields\n const autoFields: string[] = [\n ...STANDARD_FIELDS, // id, createdAt, updatedAt\n ...(softDelete ? SOFT_DELETE_FIELDS : []), // deletedAt\n ...(multiTenant ? TENANT_FIELDS : []), // workspaceId, tenantId\n ...(audit ? AUDIT_FIELDS : []), // metadata, context\n ];\n\n // Merge and deduplicate fields\n const mergedFields = [...new Set([...autoFields, ...entityFields])];\n\n // Handle multiTenant: false\n const finalGetWorkspaceId =\n multiTenant === false\n ? (_data: Record<string, unknown>) => undefined\n : (getWorkspaceId ?? DEFAULT_GET_WORKSPACE_ID);\n\n const finalGetOrgId =\n multiTenant === false ? (_data: Record<string, unknown>) => undefined : (getOrgId ?? DEFAULT_GET_ORG_ID);\n\n return {\n collection: collection ?? 'entities',\n fields: mergedFields,\n getWorkspaceId: finalGetWorkspaceId,\n getOrgId: finalGetOrgId,\n extractTitle: extractTitle ?? createDefaultExtractTitle(entityName),\n ...(rbac && { rbac }),\n ...rest,\n };\n}\n\n/**\n * Process all relationships with smart defaults\n */\nfunction processRelationships(\n relationshipOptions: Record<string, DefineRelationshipConfigOptions>\n): Record<string, GenericRelationshipConfig> {\n const relationships: Record<string, GenericRelationshipConfig> = {};\n\n for (const [relationshipName, options] of Object.entries(relationshipOptions)) {\n const { label, toField, ...rest } = options;\n\n relationships[relationshipName] = {\n toField: toField ?? 'id',\n label: label ?? generateRelationshipLabel(relationshipName),\n ...rest,\n };\n }\n\n return relationships;\n}\n\n/**\n * Log validation results and throw on errors\n */\nfunction logValidationResults(moduleName: string, validationResult: GraphValidationResult): void {\n if (validationResult.errors.length > 0) {\n logger.error(`[GraphConfig:${moduleName}] Configuration validation failed:`);\n for (const error of validationResult.errors) {\n logger.error(` - ${error.message}`, {\n type: error.type,\n entityType: error.entityType,\n relationshipKey: error.relationshipKey,\n });\n }\n throw new Error(`Graph configuration validation failed for ${moduleName}`);\n }\n\n if (validationResult.warnings.length > 0) {\n logger.warn(`[GraphConfig:${moduleName}] Configuration warnings:`);\n for (const warning of validationResult.warnings) {\n logger.warn(` - ${warning}`);\n }\n }\n\n logger.info(`[GraphConfig:${moduleName}] Configuration validated successfully`, {\n valid: validationResult.valid,\n errorCount: validationResult.errors.length,\n warningCount: validationResult.warnings.length,\n autoFieldsApplied: true,\n });\n}\n\nexport function defineGraphConfig(options: DefineGraphConfigOptions): GenericGraphConfig {\n // Process entities with smart defaults\n const entities: Record<string, GenericEntityConfig> = {};\n\n for (const [entityName, entityOptions] of Object.entries(options.entities)) {\n entities[entityName] = processEntityConfig(entityName, entityOptions, options.prismaFieldsModule);\n }\n\n // Process relationships with smart defaults\n const relationships = options.relationships ? processRelationships(options.relationships) : {};\n\n // Build final config\n const config: GenericGraphConfig = {\n moduleName: options.moduleName,\n entities,\n relationships,\n };\n\n // Validate configuration and log results\n const validationResult = validateGraphConfig(config);\n logValidationResults(config.moduleName, validationResult);\n\n // Auto-register with GraphRegistry so the Prisma graph extension\n // can emit events for these entity types without requiring explicit\n // initializeGraph() calls. This makes graph event emission work\n // automatically for any service that has a graph.config.ts.\n autoRegisterWithRegistry(config);\n\n return config;\n}\n\n/**\n * Auto-register graph config entities with GraphRegistry\n * Called automatically by defineGraphConfig() so Prisma graph extension\n * knows which entity types to monitor.\n */\nfunction autoRegisterWithRegistry(config: GenericGraphConfig): void {\n const { moduleName, entities, relationships = {} } = config;\n\n // Convert to registry format\n const registryEntities: Record<string, EntityGraphConfig> = {};\n for (const [entityType, entityConfig] of Object.entries(entities)) {\n registryEntities[entityType] = {\n fields: entityConfig.fields,\n collection: entityConfig.collection || 'entities',\n extractTitle: entityConfig.extractTitle,\n getOrgId: entityConfig.getOrgId,\n getWorkspaceId: entityConfig.getWorkspaceId,\n enabled: entityConfig.enabled,\n // Pass through RBAC config so the Prisma graph extension\n // can include RBAC metadata in entity lifecycle events\n ...(entityConfig.rbac && {\n rbac: {\n resourceTypeName: entityConfig.rbac.resourceTypeName,\n extractName: entityConfig.rbac.extractName,\n extractIdentifier: entityConfig.rbac.extractIdentifier,\n parentResourceField: entityConfig.rbac.parentResourceField,\n createResource: entityConfig.rbac.createResource,\n },\n }),\n } as EntityGraphConfig;\n }\n\n const registryRelationships: Record<string, RelationshipGraphConfig> = {};\n for (const [key, relConfig] of Object.entries(relationships)) {\n registryRelationships[key] = {\n from: relConfig.from,\n to: relConfig.to,\n fromField: relConfig.fromField,\n toField: relConfig.toField,\n label: relConfig.label,\n description: relConfig.description,\n extractMetadata: relConfig.extractMetadata,\n polymorphicTypeField: relConfig.polymorphicTypeField,\n enabled: relConfig.enabled,\n };\n }\n\n GraphRegistry.registerModule({\n moduleName,\n entities: registryEntities,\n relationships: registryRelationships,\n });\n\n logger.info(\n `[GraphConfig:${moduleName}] Auto-registered ${Object.keys(entities).length} entities with GraphRegistry`\n );\n}\n\n/**\n * Helper to create entity config with type safety\n *\n * This is optional but provides better autocomplete in IDEs.\n */\nexport function defineEntity(config: GenericEntityConfig): GenericEntityConfig {\n return config;\n}\n\n/**\n * Helper to create relationship config with type safety\n */\nexport function defineRelationship(config: GenericRelationshipConfig): GenericRelationshipConfig {\n return config;\n}\n\n/**\n * Re-export types for convenience\n */\nexport type {\n GenericGraphConfig,\n GenericEntityConfig,\n GenericRelationshipConfig,\n GraphValidationResult,\n GraphValidationError,\n};\n","/**\n * Graph Initialization System\n *\n * Handles registration of graph config with GraphRegistry and\n * automatic Prisma extension setup.\n *\n * @module graph/config/init\n * @category Graph\n */\n\nimport type { GenericGraphConfig } from './types.js';\nimport type { GraphEventEmitter } from '../middleware/prisma-extension.js';\nimport { GraphRegistry } from '../utils/registry.js';\nimport { addGraphExtension } from '../middleware/prisma-extension.js';\nimport { logger } from '../../logger/index.js';\n\n/**\n * Options for graph initialization\n */\nexport interface InitializeGraphOptions {\n /**\n * Product/module name for event metadata\n * @example 'module-tags', 'module-calendar'\n */\n productName: string;\n\n /**\n * Event emitter for publishing graph events\n * Must implement the GraphEventEmitter interface\n */\n eventEmitter: GraphEventEmitter;\n\n /**\n * Entity types to monitor (if empty, monitors all)\n * @default [] (all entities)\n */\n monitoredEntityTypes?: string[];\n\n /**\n * Whether to enable the Prisma extension\n * @default true\n */\n enabled?: boolean;\n\n /**\n * Whether to validate entity data at runtime\n * This adds overhead but catches configuration errors early\n * @default true in development, false in production\n */\n validateRuntime?: boolean;\n}\n\n/**\n * Runtime validator for entity data\n *\n * Validates that extracted data matches configuration expectations.\n * Only runs if validateRuntime is enabled.\n */\nclass RuntimeValidator {\n constructor(private config: GenericGraphConfig) {}\n\n /**\n * Validate entity data extraction\n */\n validateEntityData(\n entityType: string,\n data: Record<string, unknown>\n ): {\n valid: boolean;\n errors: string[];\n } {\n const errors: string[] = [];\n const entityConfig = this.config.entities[entityType];\n\n if (!entityConfig) {\n return { valid: true, errors: [] }; // Not configured, skip validation\n }\n\n // Check workspace ID\n try {\n const workspaceId = entityConfig.getWorkspaceId(data);\n if (!workspaceId) {\n errors.push(`Entity ${entityType}:${data['id']} has no workspaceId`);\n }\n } catch (error) {\n errors.push(`Error extracting workspaceId for ${entityType}: ${error}`);\n }\n\n // Check org ID\n try {\n const orgId = entityConfig.getOrgId(data);\n if (!orgId) {\n errors.push(`Entity ${entityType}:${data['id']} has no organizationId`);\n }\n } catch (error) {\n errors.push(`Error extracting organizationId for ${entityType}: ${error}`);\n }\n\n // Check configured fields exist\n for (const field of entityConfig.fields) {\n if (!(field in data)) {\n errors.push(`Entity ${entityType}:${data['id']} missing configured field: ${field}`);\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n }\n}\n\n/**\n * Initialize graph integration for a microservice\n *\n * This function:\n * 1. Registers the configuration with GraphRegistry\n * 2. Sets up the Prisma extension for automatic event emission\n * 3. Validates workspace boundaries\n * 4. Returns an extended Prisma client\n *\n * @param prismaClient - Base Prisma client instance\n * @param config - Graph configuration from defineGraphConfig()\n * @param options - Initialization options\n * @returns Extended Prisma client with graph event emission\n *\n * @example\n * ```typescript\n * // microservice/src/index.ts\n * import { PrismaClient } from '@prisma/client';\n * import { initializeGraph } from '@burdenoff/be-sdk/graph';\n * import { graphConfig } from './graph.config.js';\n * import { graphEventEmitter } from './events.js';\n *\n * const basePrisma = new PrismaClient();\n *\n * const prisma = initializeGraph(basePrisma, graphConfig, {\n * productName: 'module-tags',\n * eventEmitter: graphEventEmitter,\n * });\n *\n * // Now use prisma normally - events are emitted automatically\n * const tag = await prisma.universalTag.create({\n * data: { name: 'Important', workspaceId: '...' }\n * });\n * // -> entity.created event emitted automatically\n * // -> relationship.created event emitted if vocabularyId is set\n * ```\n */\nexport function initializeGraph<TPrisma>(\n prismaClient: TPrisma,\n config: GenericGraphConfig,\n options: InitializeGraphOptions\n): TPrisma {\n const { productName, eventEmitter, monitoredEntityTypes = [], enabled = true, validateRuntime } = options;\n\n // Determine if runtime validation should be enabled\n const shouldValidate = validateRuntime ?? process.env['NODE_ENV'] !== 'production';\n\n logger.info(`[GraphInit:${config.moduleName}] Initializing graph integration`, {\n productName,\n enabled,\n validateRuntime: shouldValidate,\n entities: Object.keys(config.entities).length,\n relationships: config.relationships ? Object.keys(config.relationships).length : 0,\n });\n\n if (!enabled) {\n logger.warn(`[GraphInit:${config.moduleName}] Graph integration disabled by configuration`);\n return prismaClient;\n }\n\n // Step 1: Register configuration with GraphRegistry\n registerConfigWithRegistry(config);\n\n // Step 2: Create runtime validator if enabled\n const validator = shouldValidate ? new RuntimeValidator(config) : null;\n\n // Step 3: Wrap event emitter with validation\n const wrappedEmitter: GraphEventEmitter = {\n publishEntityEvent: async (eventType, entity, context, rbac) => {\n // Runtime validation\n if (validator && (eventType === 'entity.created' || eventType === 'entity.updated')) {\n const validation = validator.validateEntityData(entity.type, entity.data);\n if (!validation.valid) {\n logger.error(`[GraphInit:${config.moduleName}] Runtime validation failed for ${entity.type}:${entity.id}`, {\n errors: validation.errors,\n });\n // Continue anyway - we log but don't block\n }\n }\n\n // Forward to actual emitter\n return eventEmitter.publishEntityEvent(eventType, entity, context, rbac);\n },\n };\n\n // Step 4: Add Prisma extension\n const extendedClient = addGraphExtension(prismaClient, {\n enabled: true,\n productName,\n eventEmitter: wrappedEmitter,\n entityTypes: monitoredEntityTypes,\n });\n\n logger.info(`[GraphInit:${config.moduleName}] Graph integration initialized successfully`);\n\n return extendedClient;\n}\n\n/**\n * Register configuration with GraphRegistry\n *\n * Converts GenericGraphConfig to ModuleGraphConfig format\n * that GraphRegistry expects.\n */\nfunction registerConfigWithRegistry(config: GenericGraphConfig): void {\n const { moduleName, entities, relationships = {} } = config;\n\n // Convert GenericEntityConfig to EntityGraphConfig\n const registryEntities: Record<\n string,\n {\n fields: string[];\n collection?: string;\n extractTitle?: (entity: Record<string, unknown>) => string | undefined;\n getOrgId?: (data: Record<string, unknown>) => string | undefined;\n getWorkspaceId?: (data: Record<string, unknown>) => string | undefined;\n enabled?: boolean;\n }\n > = {};\n\n for (const [entityType, entityConfig] of Object.entries(entities)) {\n registryEntities[entityType] = {\n fields: entityConfig.fields,\n collection: entityConfig.collection || 'entities',\n extractTitle: entityConfig.extractTitle,\n getOrgId: entityConfig.getOrgId,\n getWorkspaceId: entityConfig.getWorkspaceId,\n enabled: entityConfig.enabled,\n };\n }\n\n // Convert GenericRelationshipConfig to RelationshipGraphConfig\n const registryRelationships: Record<\n string,\n {\n from: string;\n to: string;\n fromField: string;\n toField?: string;\n label: string;\n description?: string;\n extractMetadata?: (record: Record<string, unknown>) => Record<string, unknown>;\n polymorphicTypeField?: string;\n enabled?: boolean;\n }\n > = {};\n\n for (const [key, relConfig] of Object.entries(relationships)) {\n registryRelationships[key] = {\n from: relConfig.from,\n to: relConfig.to,\n fromField: relConfig.fromField,\n toField: relConfig.toField,\n label: relConfig.label,\n description: relConfig.description,\n extractMetadata: relConfig.extractMetadata,\n polymorphicTypeField: relConfig.polymorphicTypeField,\n enabled: relConfig.enabled,\n };\n }\n\n // Register with GraphRegistry\n GraphRegistry.registerModule({\n moduleName,\n entities: registryEntities as Record<string, import('../types.js').EntityGraphConfig>,\n relationships: registryRelationships,\n });\n\n logger.info(`[GraphInit:${moduleName}] Configuration registered with GraphRegistry`);\n}\n\n/**\n * Validate that a Prisma client has been properly initialized with graph support\n *\n * This is a runtime check to ensure initializeGraph() was called.\n *\n * @param moduleName - Module name for logging\n * @returns Whether the module is registered\n */\nexport function isGraphInitialized(moduleName: string): boolean {\n const registeredModules = GraphRegistry.getRegisteredModules();\n return registeredModules.includes(moduleName);\n}\n\n/**\n * Get graph statistics for a module\n *\n * Useful for debugging and monitoring.\n */\nexport function getGraphStats(): {\n modules: number;\n entities: number;\n relationships: number;\n registeredModules: string[];\n} {\n const stats = GraphRegistry.getStats();\n const registeredModules = GraphRegistry.getRegisteredModules();\n\n return {\n modules: stats.modules,\n entities: stats.entities,\n relationships: stats.relationships,\n registeredModules,\n };\n}\n"]}