All files / core/blong-gogo/src/adapter/server/slack slackMessageSendRequestSend.ts

28.57% Statements 22/77
100% Branches 0/0
0% Functions 0/2
28.57% Lines 22/77

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 781x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x                   1x 1x                                                                                      
import type {IChatAccountMap, IChatAttachment, IChatSendParams} from '@feasibleone/blong/types';
import {handler} from '@feasibleone/blong/types';
 
import {slackMarkdown, splitSlackText} from '../../impl/markdown.ts';
 
/**
 * `slack.message.send` — the request `chat.postMessage` is made with.
 *
 * The token is read from the port's own configuration, which is the one place a secret lives: the
 * realm names an account and never sees what it authenticates with.
 */
/**
 * The sections one long answer becomes.
 *
 * A section holds 3000 characters and a message up to fifty of them, so the split is what lets a model
 * answer at length in one message rather than in a wall that Slack refuses (`@@D-730`).
 */
const sections = (text: string): unknown[] =>
    splitSlackText(text, 2_900).map(chunk => ({
        type: 'section',
        text: {type: 'mrkdwn', text: chunk},
    }));
 
const images = (attachments: IChatAttachment[] | undefined): unknown[] =>
    (attachments ?? [])
        .filter(
            attachment => attachment.url && /^image\//.test(attachment.contentType ?? 'image/*'),
        )
        .map(attachment => ({
            type: 'image',
            image_url: attachment.url,
            alt_text: attachment.title ?? attachment.filename ?? 'image',
        }));
 
export default handler(({lib: {error, slackTokenGet, slackBaseGet}}) => {
    const errors = error({
        'slack.accountMissing': {
            message: 'No Slack account {account} is configured',
            statusCode: 404,
        },
    });

    return function slackMessageSendRequestSend(
        this: {config?: {accounts?: IChatAccountMap; url?: string}},
        params: IChatSendParams,
    ) {
        const token = slackTokenGet(this.config?.accounts, params.account);
        if (!token) throw errors['slack.accountMissing']({params: {account: params.account ?? ''}});
        // A model answers in Markdown and Slack reads mrkdwn, so the text is translated before it is
        // sent; a short answer travels as the message's own text, which is what the notification shows.
        const markdown = slackMarkdown(params.text ?? '');
        const long = markdown.length > 2_900;
        const blocks = [...(long ? sections(markdown) : []), ...images(params.attachments)];
        return {
            // The account's own base, so a test account's call reaches the simulator rather than the
            // real API while the same process serves both (`@@D-687`).
            url: new URL(
                'chat.postMessage',
                slackBaseGet(this.config?.accounts, params.account, this.config?.url),
            ),
            path: 'chat.postMessage',
            method: 'POST',
            responseType: 'json',
            headers: {
                authorization: `Bearer ${token}`,
                'content-type': 'application/json; charset=utf-8',
            },
            json: {
                channel: params.conversationId,
                mrkdwn: true,
                // Slack asks for a text fallback beside blocks, for the notification and for search.
                text: markdown,
                ...(blocks.length && {blocks}),
            },
        };
    };
});