refactor(shared): reuse chat content extractor for assistant text

This commit is contained in:
Peter Steinberger
2026-02-17 00:53:38 +00:00
parent ddef3cadba
commit f452a7a60b
4 changed files with 41 additions and 39 deletions

View File

@@ -1,8 +1,13 @@
export function extractTextFromChatContent(
content: unknown,
opts?: { sanitizeText?: (text: string) => string },
opts?: {
sanitizeText?: (text: string) => string;
joinWith?: string;
normalizeText?: (text: string) => string;
},
): string | null {
const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
const normalize = opts?.normalizeText ?? ((text: string) => text.replace(/\s+/g, " ").trim());
const joinWith = opts?.joinWith ?? " ";
if (typeof content === "string") {
const value = opts?.sanitizeText ? opts.sanitizeText(content) : content;
@@ -32,6 +37,6 @@ export function extractTextFromChatContent(
}
}
const joined = normalize(chunks.join(" "));
const joined = normalize(chunks.join(joinWith));
return joined ? joined : null;
}

View File

@@ -30,6 +30,22 @@ describe("extractTextFromChatContent", () => {
}),
).toBe("Here ok");
});
it("supports custom join and normalization", () => {
expect(
extractTextFromChatContent(
[
{ type: "text", text: " hello " },
{ type: "text", text: "world " },
],
{
sanitizeText: (text) => text.trim(),
joinWith: "\n",
normalizeText: (text) => text.trim(),
},
),
).toBe("hello\nworld");
});
});
describe("shared/frontmatter", () => {