diff --git a/src/simulationMachine.tsx b/src/simulationMachine.tsx index 1156730a..1274aade 100644 --- a/src/simulationMachine.tsx +++ b/src/simulationMachine.tsx @@ -135,6 +135,11 @@ export const simulationMachine = simModel.createMachine( const serviceMap: Map = new Map(); const machines = new Set(); const rootServices = new Set(); + function addChildService(service: AnyInterpreter) { + if (!serviceMap.has(service.sessionId)) { + serviceMap.set(service.sessionId, service); + } + } function locallyInterpret(machine: AnyStateMachine) { machines.add(machine); @@ -179,6 +184,16 @@ export const simulationMachine = simModel.createMachine( sendBack(simModel.events.ERROR((e as Error).message)); } }); + } else if (event.type === 'ADDSERVICE') { + event.services.forEach((service: AnyInterpreter) => { + if (service?.sessionId) { + try { + addChildService(service); + } catch (e) { + sendBack(simModel.events.ERROR((e as Error).message)); + } + } + }); } else if (event.type === 'xstate.event') { const service = serviceMap.get(event.sessionId); if (service) { @@ -281,16 +296,25 @@ export const simulationMachine = simModel.createMachine( ], }, 'SERVICE.REGISTER': { - actions: simModel.assign({ - serviceDataMap: (ctx, { type, ...data }) => { - return produce(ctx.serviceDataMap, (draft) => { - draft[data.sessionId] = data; - }); - }, - currentSessionId: (ctx, e) => { - return ctx.currentSessionId ?? e.sessionId; - }, - }), + actions: [ + send( + (_, e) => ({ + type: 'ADDSERVICE', + services: [e.service], + }), + { to: 'proxy' }, + ), + simModel.assign({ + serviceDataMap: (ctx, { type, ...data }) => { + return produce(ctx.serviceDataMap, (draft) => { + draft[data.sessionId] = data; + }); + }, + currentSessionId: (ctx, e) => { + return ctx.currentSessionId ?? e.sessionId; + }, + }), + ], }, 'SERVICES.UNREGISTER_ALL': { actions: simModel.assign({ @@ -344,6 +368,7 @@ export const simulationMachine = simModel.createMachine( if (service.parent) { sendBack( simModel.events['SERVICE.REGISTER']({ + service: service, sessionId: service.sessionId, machine: service.machine, state: service.state || service.initialState, diff --git a/src/types.ts b/src/types.ts index 68df4587..72dcfe2f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -41,6 +41,7 @@ export type ServiceRefEvents = }; export interface ServiceData { + service?: AnyInterpreter; sessionId: string; machine: AnyStateMachine; state: AnyState;