-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
80 lines (69 loc) · 2.08 KB
/
index.ts
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
78
79
80
// Import Third-party Dependencies
import { type MorphixOptions } from "@sigyn/morphix";
import { type WebhookNotifierOptions, WebhookNotifier } from "@sigyn/notifiers";
import { type MessageAttachment } from "@slack/types";
// CONSTANTS
const kAttachmentColor = {
critical: "#FF3333",
error: "#F3840F",
warning: "#FFE333",
info: "#E7E7E7"
};
export interface SlackWebhookBodyFormat {
attachments?: MessageAttachment[];
}
class SlackNotifier extends WebhookNotifier<SlackWebhookBodyFormat> {
override contentTemplateOptions(): MorphixOptions {
return {
transform: ({ value, key }) => (key === "logql" || key === "lokiUrl" ? value : `*${value ?? "unknown"}*`),
ignoreMissing: true
};
}
async formatWebhookBody(): Promise<SlackWebhookBodyFormat> {
if (this.data.ruleConfig?.logql) {
this.data.ruleConfig.logql = this.#formatLogQL(this.data.ruleConfig.logql);
}
this.template.content = this.template.content.map((text) => {
let formattedText = text;
// Slack doesn't supports [label](url) format but <url|label> instead.
const mdUrlRegex = /\[([^[\]]+)\]\(([^()]+)\)/g;
const [url, label, link] = mdUrlRegex.exec(text) ?? [];
if (url !== undefined) {
formattedText = formattedText.replace(url, `<${link}|${label}>`);
}
return formattedText;
});
const [title, content] = await Promise.all([
this.formatTitle(),
this.formatContent()
]);
return {
attachments: [
{
mrkdwn_in: ["text"],
color: kAttachmentColor[this.data.severity],
title,
fields: [
{
title,
value: content.join("\n").replaceAll(/>(?!\s|$)/g, "›"),
short: false
}
]
}
]
};
}
#formatLogQL(logql: string): string {
return `\`${logql.replaceAll("`", "'")}\``;
}
}
export async function execute(
options: WebhookNotifierOptions
) {
const notifier = new SlackNotifier(options);
const body = await notifier.formatWebhookBody();
return notifier.execute(
body
);
}