openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
40 lines (39 loc) • 1.26 kB
JavaScript
//#region src/shared/chat-content.ts
/** Coerces arbitrary provider content values into displayable text without throwing. */
function coerceChatContentText(e) {
if (typeof e === "string") return e;
if (e == null) return "";
if (typeof e === "number" || typeof e === "boolean" || typeof e === "bigint" || typeof e === "symbol") return String(e);
if (typeof e === "object") try {
return JSON.stringify(e) ?? "";
} catch {
return "";
}
return "";
}
/** Extracts normalized plain text from string content or OpenAI-style text blocks. */
function extractTextFromChatContent(e, t) {
const n = t?.normalizeText ?? ((e) => e.replace(/\s+/g, " ").trim());
const r = t?.joinWith ?? " ";
const sanitize = (e) => {
const n = coerceChatContentText(e);
return t?.sanitizeText ? t.sanitizeText(n) : n;
};
if (typeof e === "string") {
const t = n(sanitize(e));
return t ? t : null;
}
if (!Array.isArray(e)) return null;
const i = [];
for (const t of e) {
if (!t || typeof t !== "object") continue;
if (t.type !== "text") continue;
const e = t.text;
const n = sanitize(e);
if (n.trim()) i.push(n);
}
const a = n(i.join(r));
return a ? a : null;
}
//#endregion
export { extractTextFromChatContent as n, coerceChatContentText as t };