|
| 1 | +import { TSendMessageParams } from '../types'; |
| 2 | +import { TLinkedApiActionError } from '../types/errors'; |
| 3 | +import type { |
| 4 | + TActionResponse, |
| 5 | + TWorkflowCompletion, |
| 6 | + TWorkflowDefinition, |
| 7 | + TWorkflowSingleData, |
| 8 | +} from '../types/workflows'; |
| 9 | + |
| 10 | +import { BaseMapper, TMappedResponse } from './base-mapper.abstract'; |
| 11 | + |
| 12 | +export class SendMessageMapper extends BaseMapper<TSendMessageParams, void> { |
| 13 | + public mapRequest(params: TSendMessageParams): TWorkflowDefinition { |
| 14 | + const { manageConversation, ...rest } = params; |
| 15 | + |
| 16 | + const definition: Record<string, unknown> = { |
| 17 | + actionType: 'st.sendMessage', |
| 18 | + ...rest, |
| 19 | + }; |
| 20 | + |
| 21 | + // The child st.manageConversation acts on the conversation this message was sent into, so it |
| 22 | + // carries only `operation` — no threadId. Core rejects a threadId on a child manageConversation. |
| 23 | + // Guard on `operation` so an empty passthrough (e.g. Make sending `{ operation: '' }`) is ignored. |
| 24 | + if (manageConversation?.operation) { |
| 25 | + definition.then = { |
| 26 | + actionType: 'st.manageConversation', |
| 27 | + operation: manageConversation.operation, |
| 28 | + }; |
| 29 | + } |
| 30 | + |
| 31 | + return definition as unknown as TWorkflowDefinition; |
| 32 | + } |
| 33 | + |
| 34 | + public mapResponse(completion: TWorkflowCompletion): TMappedResponse<void> { |
| 35 | + if (Array.isArray(completion)) { |
| 36 | + return { |
| 37 | + data: undefined, |
| 38 | + errors: completion.map((action) => action.error).filter(Boolean) as TLinkedApiActionError[], |
| 39 | + }; |
| 40 | + } |
| 41 | + |
| 42 | + const errors: TLinkedApiActionError[] = []; |
| 43 | + |
| 44 | + if (completion.error) { |
| 45 | + errors.push(completion.error); |
| 46 | + } |
| 47 | + |
| 48 | + const thenActions = (completion.data as TWorkflowSingleData | undefined)?.then; |
| 49 | + if (thenActions) { |
| 50 | + const childActions = Array.isArray(thenActions) ? thenActions : [thenActions]; |
| 51 | + for (const child of childActions as TActionResponse[]) { |
| 52 | + if (child.error) { |
| 53 | + errors.push(child.error); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return { |
| 59 | + data: undefined, |
| 60 | + errors, |
| 61 | + }; |
| 62 | + } |
| 63 | +} |
0 commit comments