Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(modules): decouple engine-only consumers from SessionService
Yudhi Armyndharis4470a417d3fc
diff --git a/src/engine/engine-registry.service.spec.ts b/src/engine/engine-registry.service.spec.tsindex 9be6efc75..34473153b 100644--- a/src/engine/engine-registry.service.spec.ts+++ b/src/engine/engine-registry.service.spec.ts@@ -117,9 +117,9 @@ describe('EngineRegistry', () => {});it('throws the caller-supplied error so each API keeps its documented status', () => {- expect(() => registry.require('s1', () => new NotFoundException('Session s1 not found or not connected'))).toThrow(- NotFoundException,- );+ expect(() =>+ registry.require('s1', () => new NotFoundException('Session s1 not found or not connected')),+ ).toThrow(NotFoundException);});it('does not build the error when the engine is present', () => {diff --git a/src/modules/call/call.module.ts b/src/modules/call/call.module.tsindex be2b3e2e8..f9766468a 100644--- a/src/modules/call/call.module.ts+++ b/src/modules/call/call.module.ts@@ -1,10 +1,8 @@import { Module } from '@nestjs/common';import { CallController } from './call.controller';import { CallService } from './call.service';-import { SessionModule } from '../session/session.module';@Module({- imports: [SessionModule],controllers: [CallController],providers: [CallService],exports: [CallService],diff --git a/src/modules/call/call.service.spec.ts b/src/modules/call/call.service.spec.tsindex c85a0afe8..7974b941e 100644--- a/src/modules/call/call.service.spec.ts+++ b/src/modules/call/call.service.spec.ts@@ -1,13 +1,14 @@import { BadRequestException } from '@nestjs/common';import { CallService } from './call.service';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import { CallNotFoundError } from '../../common/errors/call-not-found.error';describe('CallService', () => {const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {- const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;- return new CallService(sessionService);+ const engines = new EngineRegistry();+ if (engine) engines.set('s1', engine as IWhatsAppEngine);+ return new CallService(engines);};it('throws 400 "Session is not started" when the engine is missing (guard preserved)', () => {diff --git a/src/modules/call/call.service.ts b/src/modules/call/call.service.tsindex e10196284..45766aa84 100644--- a/src/modules/call/call.service.ts+++ b/src/modules/call/call.service.ts@@ -1,5 +1,5 @@-import { Injectable, BadRequestException } from '@nestjs/common';-import { SessionService } from '../session/session.service';+import { Injectable } from '@nestjs/common';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';/**@@ -9,14 +9,11 @@ import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interfa*/@Injectable()export class CallService {- constructor(private readonly sessionService: SessionService) {}+ constructor(private readonly engines: EngineRegistry) {}private getEngine(sessionId: string): IWhatsAppEngine {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new BadRequestException('Session is not started');- }- return engine;+ // EngineRegistry.require()'s default is this exact 400 "Session is not started".+ return this.engines.require(sessionId);}/**diff --git a/src/modules/catalog/catalog.module.ts b/src/modules/catalog/catalog.module.tsindex 077ee1f1b..161cdd60b 100644--- a/src/modules/catalog/catalog.module.ts+++ b/src/modules/catalog/catalog.module.ts@@ -1,10 +1,8 @@import { Module } from '@nestjs/common';import { CatalogController } from './catalog.controller';import { CatalogService } from './catalog.service';-import { SessionModule } from '../session/session.module';@Module({- imports: [SessionModule],controllers: [CatalogController],providers: [CatalogService],exports: [CatalogService],diff --git a/src/modules/catalog/catalog.service.ts b/src/modules/catalog/catalog.service.tsindex 8d1beef49..505dc880c 100644--- a/src/modules/catalog/catalog.service.ts+++ b/src/modules/catalog/catalog.service.ts@@ -1,5 +1,5 @@import { Injectable, NotFoundException } from '@nestjs/common';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import type {Catalog,Product,@@ -9,45 +9,45 @@ import type {@Injectable()export class CatalogService {- constructor(private readonly sessionService: SessionService) {}+ constructor(private readonly engines: EngineRegistry) {}async getCatalog(sessionId: string): Promise<Catalog | null> {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new NotFoundException(`Session ${sessionId} not found or not connected`);- }+ const engine = this.engines.require(+ sessionId,+ () => new NotFoundException(`Session ${sessionId} not found or not connected`),+ );return engine.getCatalog();}async getProducts(sessionId: string, page = 1, limit = 20): Promise<PaginatedProducts> {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new NotFoundException(`Session ${sessionId} not found or not connected`);- }+ const engine = this.engines.require(+ sessionId,+ () => new NotFoundException(`Session ${sessionId} not found or not connected`),+ );return engine.getProducts({ page, limit });}async getProduct(sessionId: string, productId: string): Promise<Product | null> {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new NotFoundException(`Session ${sessionId} not found or not connected`);- }+ const engine = this.engines.require(+ sessionId,+ () => new NotFoundException(`Session ${sessionId} not found or not connected`),+ );return engine.getProduct(productId);}async sendProduct(sessionId: string, chatId: string, productId: string, body?: string): Promise<MessageResult> {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new NotFoundException(`Session ${sessionId} not found or not connected`);- }+ const engine = this.engines.require(+ sessionId,+ () => new NotFoundException(`Session ${sessionId} not found or not connected`),+ );return engine.sendProduct(chatId, productId, body);}async sendCatalog(sessionId: string, chatId: string, body?: string): Promise<MessageResult> {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new NotFoundException(`Session ${sessionId} not found or not connected`);- }+ const engine = this.engines.require(+ sessionId,+ () => new NotFoundException(`Session ${sessionId} not found or not connected`),+ );return engine.sendCatalog(chatId, body);}}diff --git a/src/modules/channel/channel.module.ts b/src/modules/channel/channel.module.tsindex 2d9f926f9..c72dbc82f 100644--- a/src/modules/channel/channel.module.ts+++ b/src/modules/channel/channel.module.ts@@ -1,10 +1,8 @@import { Module } from '@nestjs/common';import { ChannelController } from './channel.controller';import { ChannelService } from './channel.service';-import { SessionModule } from '../session/session.module';@Module({- imports: [SessionModule],controllers: [ChannelController],providers: [ChannelService],})diff --git a/src/modules/channel/channel.service.spec.ts b/src/modules/channel/channel.service.spec.tsindex 1eb576069..b43193976 100644--- a/src/modules/channel/channel.service.spec.ts+++ b/src/modules/channel/channel.service.spec.ts@@ -1,12 +1,13 @@import { BadRequestException, NotFoundException } from '@nestjs/common';import { ChannelService } from './channel.service';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';describe('ChannelService', () => {const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {- const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;- return new ChannelService(sessionService);+ const engines = new EngineRegistry();+ if (engine) engines.set('s1', engine as IWhatsAppEngine);+ return new ChannelService(engines);};it('throws 400 when the session is not started', () => {diff --git a/src/modules/channel/channel.service.ts b/src/modules/channel/channel.service.tsindex d7e902775..b2c385fae 100644--- a/src/modules/channel/channel.service.ts+++ b/src/modules/channel/channel.service.ts@@ -1,5 +1,5 @@-import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';-import { SessionService } from '../session/session.service';+import { Injectable, NotFoundException } from '@nestjs/common';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';/**@@ -10,14 +10,11 @@ import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interfaexport class ChannelService {private static readonly MAX_CHANNEL_HISTORY_LIMIT = 100;- constructor(private readonly sessionService: SessionService) {}+ constructor(private readonly engines: EngineRegistry) {}private getEngine(sessionId: string): IWhatsAppEngine {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new BadRequestException('Session is not started');- }- return engine;+ // EngineRegistry.require()'s default is this exact 400 "Session is not started".+ return this.engines.require(sessionId);}getSubscribedChannels(sessionId: string) {diff --git a/src/modules/contact/contact.module.ts b/src/modules/contact/contact.module.tsindex cdfb0736f..d19640493 100644--- a/src/modules/contact/contact.module.ts+++ b/src/modules/contact/contact.module.ts@@ -1,10 +1,8 @@import { Module } from '@nestjs/common';import { ContactController } from './contact.controller';import { ContactService } from './contact.service';-import { SessionModule } from '../session/session.module';@Module({- imports: [SessionModule],controllers: [ContactController],providers: [ContactService],exports: [ContactService],diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.tsindex 87133066e..f37282ed9 100644--- a/src/modules/contact/contact.service.spec.ts+++ b/src/modules/contact/contact.service.spec.ts@@ -1,12 +1,13 @@import { BadRequestException, NotFoundException } from '@nestjs/common';import { ContactService } from './contact.service';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';describe('ContactService', () => {const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {- const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;- return new ContactService(sessionService);+ const engines = new EngineRegistry();+ if (engine) engines.set('s1', engine as IWhatsAppEngine);+ return new ContactService(engines);};it('throws 400 when the session is not started', () => {diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.tsindex 70ef26125..4177bfaf3 100644--- a/src/modules/contact/contact.service.ts+++ b/src/modules/contact/contact.service.ts@@ -1,5 +1,5 @@-import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';-import { SessionService } from '../session/session.service';+import { Injectable, NotFoundException } from '@nestjs/common';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import { paginate, ListOptions } from '../../common/utils/paginate';@@ -9,14 +9,11 @@ import { paginate, ListOptions } from '../../common/utils/paginate';*/@Injectable()export class ContactService {- constructor(private readonly sessionService: SessionService) {}+ constructor(private readonly engines: EngineRegistry) {}private getEngine(sessionId: string): IWhatsAppEngine {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new BadRequestException('Session is not started');- }- return engine;+ // EngineRegistry.require()'s default is this exact 400 "Session is not started".+ return this.engines.require(sessionId);}getContacts(sessionId: string, opts: ListOptions = {}) {diff --git a/src/modules/group/group.module.ts b/src/modules/group/group.module.tsindex feef5f9e0..f09827e8f 100644--- a/src/modules/group/group.module.ts+++ b/src/modules/group/group.module.ts@@ -1,10 +1,8 @@import { Module } from '@nestjs/common';import { GroupController } from './group.controller';import { GroupService } from './group.service';-import { SessionModule } from '../session/session.module';@Module({- imports: [SessionModule],controllers: [GroupController],providers: [GroupService],exports: [GroupService],diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.tsindex 6c02546d3..bce84a5e3 100644--- a/src/modules/group/group.service.spec.ts+++ b/src/modules/group/group.service.spec.ts@@ -1,14 +1,15 @@import { BadRequestException, HttpException, NotFoundException } from '@nestjs/common';import { GroupService } from './group.service';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { EngineRefusedError } from '../../common/errors/engine-refused.error';describe('GroupService', () => {const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {- const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;- return new GroupService(sessionService);+ const engines = new EngineRegistry();+ if (engine) engines.set('s1', engine as IWhatsAppEngine);+ return new GroupService(engines);};it('throws 400 "Session is not started" when the engine is missing (guard preserved)', () => {diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.tsindex 27d1ab31d..01a5cfdd0 100644--- a/src/modules/group/group.service.ts+++ b/src/modules/group/group.service.ts@@ -1,5 +1,5 @@import { Injectable, BadRequestException, HttpException, HttpStatus, NotFoundException } from '@nestjs/common';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import { paginate, ListOptions } from '../../common/utils/paginate';@@ -10,14 +10,11 @@ import { paginate, ListOptions } from '../../common/utils/paginate';*/@Injectable()export class GroupService {- constructor(private readonly sessionService: SessionService) {}+ constructor(private readonly engines: EngineRegistry) {}private getEngine(sessionId: string): IWhatsAppEngine {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new BadRequestException('Session is not started');- }- return engine;+ // EngineRegistry.require()'s default is this exact 400 "Session is not started".+ return this.engines.require(sessionId);}getGroups(sessionId: string, opts: ListOptions = {}) {diff --git a/src/modules/label/label.module.ts b/src/modules/label/label.module.tsindex 9b6a38dda..9ad339e0a 100644--- a/src/modules/label/label.module.ts+++ b/src/modules/label/label.module.ts@@ -1,10 +1,8 @@import { Module } from '@nestjs/common';import { LabelController } from './label.controller';import { LabelService } from './label.service';-import { SessionModule } from '../session/session.module';@Module({- imports: [SessionModule],controllers: [LabelController],providers: [LabelService],})diff --git a/src/modules/label/label.service.spec.ts b/src/modules/label/label.service.spec.tsindex 4d5518c57..1c0f6e4c5 100644--- a/src/modules/label/label.service.spec.ts+++ b/src/modules/label/label.service.spec.ts@@ -1,12 +1,13 @@import { BadRequestException, NotFoundException } from '@nestjs/common';import { LabelService } from './label.service';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';describe('LabelService', () => {const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {- const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;- return new LabelService(sessionService);+ const engines = new EngineRegistry();+ if (engine) engines.set('s1', engine as IWhatsAppEngine);+ return new LabelService(engines);};it('throws 400 when the session is not started', () => {diff --git a/src/modules/label/label.service.ts b/src/modules/label/label.service.tsindex 9a73bdf14..1e618aef5 100644--- a/src/modules/label/label.service.ts+++ b/src/modules/label/label.service.ts@@ -1,5 +1,5 @@-import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';-import { SessionService } from '../session/session.service';+import { Injectable, NotFoundException } from '@nestjs/common';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';/**@@ -8,14 +8,11 @@ import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interfa*/@Injectable()export class LabelService {- constructor(private readonly sessionService: SessionService) {}+ constructor(private readonly engines: EngineRegistry) {}private getEngine(sessionId: string): IWhatsAppEngine {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new BadRequestException('Session is not started');- }- return engine;+ // EngineRegistry.require()'s default is this exact 400 "Session is not started".+ return this.engines.require(sessionId);}getLabels(sessionId: string) {diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex b8c2ae850..8d6afa23e 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -11,7 +11,8 @@ import {import { MessageBatch, BatchStatus, BatchMessageStatus, BatchMessageResult } from './entities/message-batch.entity';import { MessageStatus } from './entities/message.entity';import { SendBulkMessageDto } from './dto/bulk-message.dto';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';+import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import { MessageService } from './message.service';import { HookManager } from '../../core/hooks';import { SsrfBlockedError } from '../../common/security/ssrf-guard';@@ -67,7 +68,7 @@ describe('BulkMessageService.onApplicationBootstrap', () => {providers: [BulkMessageService,{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },- { provide: SessionService, useValue: { getEngine: jest.fn() } },+ EngineRegistry,{ provide: MessageService, useValue: { saveOutgoingMessage: jest.fn() } },{provide: HookManager,@@ -126,7 +127,7 @@ describe('BulkMessageService.processBatch', () => {sendVideoMessage?: jest.Mock;sendAudioMessage?: jest.Mock;};- let sessionService: { getEngine: jest.Mock; findOne: jest.Mock };+ let engines: EngineRegistry;let hookManager: { execute: jest.Mock };const makeBatch = (messageCount: number): MessageBatch =>@@ -148,10 +149,8 @@ describe('BulkMessageService.processBatch', () => {beforeEach(async () => {engine = { sendTextMessage: jest.fn().mockResolvedValue({ id: 'wa1', timestamp: 111 }) };- sessionService = {- getEngine: jest.fn().mockReturnValue(engine),- findOne: jest.fn().mockResolvedValue({ phone: '628' }),- };+ engines = new EngineRegistry();+ engines.set('s1', engine as unknown as IWhatsAppEngine);messageService = { saveOutgoingMessage: jest.fn().mockResolvedValue(undefined) };hookManager = {execute: jest.fn().mockImplementation((_e: string, data: unknown) => Promise.resolve({ continue: true, data })),@@ -166,7 +165,7 @@ describe('BulkMessageService.processBatch', () => {providers: [BulkMessageService,{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },- { provide: SessionService, useValue: sessionService },+ { provide: EngineRegistry, useValue: engines },{ provide: MessageService, useValue: messageService },{ provide: HookManager, useValue: hookManager },],@@ -197,7 +196,7 @@ describe('BulkMessageService.processBatch', () => {it('releases the in-flight marker when the engine is missing (no processingBatches leak)', async () => {repo.findOne.mockResolvedValue(makeBatch(1));- sessionService.getEngine.mockReturnValue(undefined); // engine-not-found → early-return path+ engines.delete('s1'); // engine-not-found → early-return pathawait runProcessBatch();@@ -578,7 +577,7 @@ describe('BulkMessageService.cancelBatch', () => {providers: [BulkMessageService,{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },- { provide: SessionService, useValue: {} },+ EngineRegistry,{ provide: MessageService, useValue: {} },{ provide: HookManager, useValue: { execute: jest.fn() } },],@@ -634,7 +633,7 @@ describe('BulkMessageService.cancelBatch', () => {describe('BulkMessageService.createBatch base64 media cap', () => {let service: BulkMessageService;let repo: { findOne: jest.Mock; save: jest.Mock; create: jest.Mock; update: jest.Mock };- let sessionService: { getEngine: jest.Mock };+ let engines: EngineRegistry;let messageService: { saveOutgoingMessage: jest.Mock };beforeEach(async () => {@@ -644,13 +643,16 @@ describe('BulkMessageService.createBatch base64 media cap', () => {create: jest.fn().mockImplementation((b: MessageBatch) => Object.assign({ id: 'b1' }, b)),update: jest.fn().mockResolvedValue({ affected: 1 }),};- sessionService = { getEngine: jest.fn().mockReturnValue({}) };+ engines = new EngineRegistry();+ // These suites exercise batch bookkeeping across several session ids, so every session is+ // "started" here; the engine itself is never called.+ for (const id of ['s1', 's2']) engines.set(id, {} as IWhatsAppEngine);messageService = { saveOutgoingMessage: jest.fn().mockResolvedValue(undefined) };const module: TestingModule = await Test.createTestingModule({providers: [BulkMessageService,{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },- { provide: SessionService, useValue: sessionService },+ { provide: EngineRegistry, useValue: engines },{ provide: MessageService, useValue: messageService },{provide: HookManager,@@ -787,7 +789,7 @@ describe('BulkMessageService.createBatch base64 media cap', () => {it('runs the engine once per exact duplicate entry across the full create→process path', async () => {const engine = { sendTextMessage: jest.fn().mockResolvedValue({ id: 'wa', timestamp: 1 }) };- sessionService.getEngine.mockReturnValue(engine);+ engines.set('s1', engine as unknown as IWhatsAppEngine);const dto = {messages: [{ chatId: '[email protected]', type: 'text' as const, content: { text: 'first' } },@@ -813,7 +815,7 @@ describe('BulkMessageService.createBatch base64 media cap', () => {sendTextMessage: jest.fn().mockResolvedValue({ id: 'wa-t', timestamp: 1 }),sendImageMessage: jest.fn().mockResolvedValue({ id: 'wa-i', timestamp: 2 }),};- sessionService.getEngine.mockReturnValue(engine);+ engines.set('s1', engine as unknown as IWhatsAppEngine);const dto = {messages: [{ chatId: '[email protected]', type: 'text' as const, content: { text: 'part 1' } },diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex fa207b689..1b7d93997 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -11,7 +11,7 @@ import {} from './entities/message-batch.entity';import { SendBulkMessageDto } from './dto/bulk-message.dto';import { MessageStatus } from './entities/message.entity';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import { MessageService } from './message.service';import { HookManager } from '../../core/hooks';import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';@@ -79,7 +79,7 @@ export class BulkMessageService implements OnApplicationBootstrap {constructor(@InjectRepository(MessageBatch, 'data')private readonly batchRepository: Repository<MessageBatch>,- private readonly sessionService: SessionService,+ private readonly engines: EngineRegistry,private readonly messageService: MessageService,private readonly hookManager: HookManager,) {}@@ -105,11 +105,8 @@ export class BulkMessageService implements OnApplicationBootstrap {}async createBatch(sessionId: string, dto: SendBulkMessageDto): Promise<MessageBatch> {- // Validate session exists- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new BadRequestException(`Session '${sessionId}' is not active`);- }+ // Validate the session is started (guard only — the batch is sent later, by drainBatch).+ this.engines.require(sessionId, () => new BadRequestException(`Session '${sessionId}' is not active`));// Collapse exact duplicate entries — same chatId, type, content, and variables; first// occurrence wins, order preserved. A true repeat would only re-run the engine (and the@@ -300,7 +297,7 @@ export class BulkMessageService implements OnApplicationBootstrap {return;}- const engine = this.sessionService.getEngine(batch.sessionId);+ const engine = this.engines.get(batch.sessionId);if (!engine) {batch.status = BatchStatus.FAILED;batch.completedAt = new Date();diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 1c4de0924..cde0b5aa7 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -5,6 +5,8 @@ import { BadRequestException, NotFoundException, PayloadTooLargeException } fromimport { MessageService } from './message.service';import { Message, MessageDirection, MessageStatus } from './entities/message.entity';import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';+import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import { HookManager } from '../../core/hooks';import { TemplateService } from '../template/template.service';import { Template } from '../template/entities/template.entity';@@ -39,6 +41,7 @@ describe('MessageService', () => {let service: MessageService;let repository: jest.Mocked<Partial<Repository<Message>>>;let sessionService: jest.Mocked<Partial<SessionService>>;+ let engines: EngineRegistry;let hookManager: jest.Mocked<Partial<HookManager>>;let templateService: jest.Mocked<Partial<TemplateService>>;let lidMappingStore: { lidsForPhone: jest.Mock; getCached: jest.Mock };@@ -67,11 +70,13 @@ describe('MessageService', () => {mockEngine = createMockEngine();sessionService = {- getEngine: jest.fn().mockReturnValue(mockEngine),findOne: jest.fn().mockResolvedValue({ id: 'sess-1', phone: '628123456789' }),recordOutboundMessageEdit: jest.fn().mockResolvedValue(undefined),};+ engines = new EngineRegistry();+ engines.set('sess-1', mockEngine as unknown as IWhatsAppEngine);+hookManager = {// Echo the input straight back so the message:sending gate is a pass-through by default; specific// tests override with continue:false (block) or a modified input.@@ -91,6 +96,7 @@ describe('MessageService', () => {MessageService,{ provide: getRepositoryToken(Message, 'data'), useValue: repository },{ provide: SessionService, useValue: sessionService },+ { provide: EngineRegistry, useValue: engines },{ provide: HookManager, useValue: hookManager },{ provide: TemplateService, useValue: templateService },{ provide: LidMappingStoreService, useValue: lidMappingStore },@@ -268,7 +274,7 @@ describe('MessageService', () => {});it('should throw BadRequestException if session is not active', async () => {- (sessionService.getEngine as jest.Mock).mockReturnValue(undefined);+ engines.delete('sess-1');await expect(service.sendText('inactive', { chatId: '[email protected]', text: 'hello' })).rejects.toThrow(BadRequestException,@@ -389,10 +395,11 @@ describe('MessageService', () => {it('honors a configured template.renderMaxChars override', async () => {const configService = {get: (key: string, fallback: unknown) => (key === 'template.renderMaxChars' ? 10 : fallback),- } as unknown as ConstructorParameters<typeof MessageService>[5];+ } as unknown as ConstructorParameters<typeof MessageService>[6];const capped = new MessageService(repository as Repository<Message>,sessionService as unknown as SessionService,+ engines,hookManager as HookManager,templateService as unknown as TemplateService,lidMappingStore as unknown as LidMappingStoreService,@@ -1303,7 +1310,7 @@ describe('MessageService', () => {});it('throws BadRequestException when the session is not started', async () => {- (sessionService.getEngine as jest.Mock).mockReturnValue(undefined);+ engines.delete('sess-1');await expect(service.editMessage('sess-1', { chatId: '[email protected]', messageId: 'wa-msg-1', body: 'edited' }),).rejects.toBeInstanceOf(BadRequestException);diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 26047f22f..5ffdbb921 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -4,6 +4,7 @@ import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { QueryDeepPartialEntity } from 'typeorm';import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import { SendTextMessageDto, SendMediaMessageDto, SendAudioMessageDto, MessageResponseDto } from './dto';import { SendTemplateMessageDto } from './dto/send-template.dto';import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';@@ -53,6 +54,7 @@ export class MessageService {@InjectRepository(Message, 'data')private readonly messageRepository: Repository<Message>,private readonly sessionService: SessionService,+ private readonly engines: EngineRegistry,private readonly hookManager: HookManager,private readonly templateService: TemplateService,private readonly lidMappingStore: LidMappingStoreService,@@ -765,11 +767,10 @@ export class MessageService {}private getEngine(sessionId: string) {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new BadRequestException(`Session '${sessionId}' is not active. Start the session first.`);- }- return engine;+ return this.engines.require(+ sessionId,+ () => new BadRequestException(`Session '${sessionId}' is not active. Start the session first.`),+ );}/**diff --git a/src/modules/profile/profile.module.ts b/src/modules/profile/profile.module.tsindex 409aa6e60..4300ce793 100644--- a/src/modules/profile/profile.module.ts+++ b/src/modules/profile/profile.module.ts@@ -1,10 +1,8 @@import { Module } from '@nestjs/common';import { ProfileController } from './profile.controller';import { ProfileService } from './profile.service';-import { SessionModule } from '../session/session.module';@Module({- imports: [SessionModule],controllers: [ProfileController],providers: [ProfileService],exports: [ProfileService],diff --git a/src/modules/profile/profile.service.spec.ts b/src/modules/profile/profile.service.spec.tsindex 5d349c203..160e2ed58 100644--- a/src/modules/profile/profile.service.spec.ts+++ b/src/modules/profile/profile.service.spec.ts@@ -1,12 +1,13 @@import { BadRequestException } from '@nestjs/common';import { ProfileService } from './profile.service';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine, MediaInput } from '../../engine/interfaces/whatsapp-engine.interface';describe('ProfileService', () => {const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {- const sessionService = { getEngine: jest.fn().mockReturnValue(engine) } as unknown as SessionService;- return new ProfileService(sessionService);+ const engines = new EngineRegistry();+ if (engine) engines.set('s1', engine as IWhatsAppEngine);+ return new ProfileService(engines);};it('throws 400 "Session is not started" when the engine is missing (guard preserved)', () => {diff --git a/src/modules/profile/profile.service.ts b/src/modules/profile/profile.service.tsindex 846e3c2f6..ae605cd1f 100644--- a/src/modules/profile/profile.service.ts+++ b/src/modules/profile/profile.service.ts@@ -1,5 +1,5 @@import { Injectable, BadRequestException } from '@nestjs/common';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import { IWhatsAppEngine, MediaInput } from '../../engine/interfaces/whatsapp-engine.interface';import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';import { SetProfilePictureDto } from './dto/profile.dto';@@ -10,14 +10,11 @@ import { SetProfilePictureDto } from './dto/profile.dto';*/@Injectable()export class ProfileService {- constructor(private readonly sessionService: SessionService) {}+ constructor(private readonly engines: EngineRegistry) {}private getEngine(sessionId: string): IWhatsAppEngine {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new BadRequestException('Session is not started');- }- return engine;+ // EngineRegistry.require()'s default is this exact 400 "Session is not started".+ return this.engines.require(sessionId);}setProfileName(sessionId: string, name: string) {diff --git a/src/modules/status/status.module.ts b/src/modules/status/status.module.tsindex cfb2e5767..258ec8040 100644--- a/src/modules/status/status.module.ts+++ b/src/modules/status/status.module.ts@@ -1,11 +1,10 @@import { Module } from '@nestjs/common';import { StatusController } from './status.controller';import { StatusService } from './status.service';-import { SessionModule } from '../session/session.module';import { StatusStoreModule } from '../status-store/status-store.module';@Module({- imports: [SessionModule, StatusStoreModule],+ imports: [StatusStoreModule],controllers: [StatusController],providers: [StatusService],exports: [StatusService],diff --git a/src/modules/status/status.service.spec.ts b/src/modules/status/status.service.spec.tsindex 3d4679a7b..4f9f03f06 100644--- a/src/modules/status/status.service.spec.ts+++ b/src/modules/status/status.service.spec.ts@@ -1,6 +1,7 @@import { BadRequestException, NotFoundException, PayloadTooLargeException } from '@nestjs/common';import { StatusService } from './status.service';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import { StatusStoreService } from '../status-store/status-store.service';import { StorageService } from '../../common/storage/storage.service';import { HookManager } from '../../core/hooks';@@ -14,7 +15,12 @@ describe('StatusService media validation and selection', () => {postImageStatus: jest.fn().mockResolvedValue({ id: 'image-status' }),postVideoStatus: jest.fn().mockResolvedValue({ id: 'video-status' }),};- const sessionService = { getEngine: jest.fn().mockReturnValue(engine) };+ const engines = new EngineRegistry();+ // Both ids the tests below post from; the store-only paths ('sess') never reach the engine.+ engines.set('s1', engine as unknown as IWhatsAppEngine);+ engines.set('sess', engine as unknown as IWhatsAppEngine);+ // Asserts the store-backed read paths never resolve an engine at all.+ const requireSpy = jest.spyOn(engines, 'require');// Pass-through gate: continue, input unchanged. The blocking/rewriting behaviour has its own// tests below.const passThrough = (_event: string, data: unknown) => Promise.resolve({ continue: true, data });@@ -22,7 +28,7 @@ describe('StatusService media validation and selection', () => {const store = { list: jest.fn(), listByContact: jest.fn(), getMedia: jest.fn() };const storageService = { getFile: jest.fn() };const service = new StatusService(- sessionService as unknown as SessionService,+ engines,hookManager as unknown as HookManager,store as unknown as StatusStoreService,storageService as unknown as StorageService,@@ -41,7 +47,7 @@ describe('StatusService media validation and selection', () => {expect(out).toEqual([{ id: 'w1' }]);expect(store.list).toHaveBeenCalledWith('sess');- expect(sessionService.getEngine).not.toHaveBeenCalled();+ expect(requireSpy).not.toHaveBeenCalled();});it('reads a contact statuses from the store, not the engine', async () => {@@ -51,7 +57,7 @@ describe('StatusService media validation and selection', () => {expect(out).toEqual([{ id: 'w2' }]);expect(store.listByContact).toHaveBeenCalledWith('sess', '[email protected]');- expect(sessionService.getEngine).not.toHaveBeenCalled();+ expect(requireSpy).not.toHaveBeenCalled();});});diff --git a/src/modules/status/status.service.ts b/src/modules/status/status.service.tsindex 66db07ada..e5cec1b46 100644--- a/src/modules/status/status.service.ts+++ b/src/modules/status/status.service.ts@@ -1,5 +1,5 @@import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';-import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';import { StatusStoreService } from '../status-store/status-store.service';import { StorageService } from '../../common/storage/storage.service';import type { Status, StatusResult, StatusPostOptions } from '../../engine/interfaces/whatsapp-engine.interface';@@ -16,7 +16,7 @@ export class StatusService {// HookManager comes from the @Global() HooksModule, StorageService from the @Global()// StorageModule — neither needs a module import here.constructor(- private readonly sessionService: SessionService,+ private readonly engines: EngineRegistry,private readonly hookManager: HookManager,private readonly store: StatusStoreService,private readonly storageService: StorageService,@@ -82,10 +82,10 @@ export class StatusService {}async postTextStatus(sessionId: string, text: string, options: StatusPostOptions): Promise<StatusResult> {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new NotFoundException(`Session ${sessionId} not found or not connected`);- }+ const engine = this.engines.require(+ sessionId,+ () => new NotFoundException(`Session ${sessionId} not found or not connected`),+ );const gated = await this.gate(sessionId, 'status-text', { text, options });return engine.postTextStatus(gated.text, gated.options);}@@ -102,10 +102,10 @@ export class StatusService {throw new BadRequestException('Either url or base64 must be provided');}assertBase64WithinMediaCap(base64);- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new NotFoundException(`Session ${sessionId} not found or not connected`);- }+ const engine = this.engines.require(+ sessionId,+ () => new NotFoundException(`Session ${sessionId} not found or not connected`),+ );const gated = await this.gate(sessionId, 'status-image', {media: { mimetype: mimetype ?? 'image/jpeg', data: base64 || url || '' },options,@@ -125,10 +125,10 @@ export class StatusService {throw new BadRequestException('Either url or base64 must be provided');}assertBase64WithinMediaCap(base64);- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new NotFoundException(`Session ${sessionId} not found or not connected`);- }+ const engine = this.engines.require(+ sessionId,+ () => new NotFoundException(`Session ${sessionId} not found or not connected`),+ );const gated = await this.gate(sessionId, 'status-video', {media: { mimetype: mimetype ?? 'video/mp4', data: base64 || url || '' },options,@@ -137,10 +137,10 @@ export class StatusService {}async deleteStatus(sessionId: string, statusId: string): Promise<void> {- const engine = this.sessionService.getEngine(sessionId);- if (!engine) {- throw new NotFoundException(`Session ${sessionId} not found or not connected`);- }+ const engine = this.engines.require(+ sessionId,+ () => new NotFoundException(`Session ${sessionId} not found or not connected`),+ );return engine.deleteStatus(statusId);}}