Move image extensions, MIME types, and size limit into a dedicated constants module. Extract JSON-from-text parsing into a pure utility function for reuse across the codebase.
20 lines
574 B
TypeScript
20 lines
574 B
TypeScript
/**
|
|
* Extract JSON from text that may contain prose, markdown code blocks, or raw JSON.
|
|
* Pure function — same input = same output, no side effects.
|
|
*/
|
|
export const extractJsonFromText = (text: string): unknown => {
|
|
try {
|
|
return JSON.parse(text);
|
|
} catch {
|
|
const codeBlockMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/);
|
|
if (codeBlockMatch) {
|
|
return JSON.parse(codeBlockMatch[1].trim());
|
|
}
|
|
const arrayMatch = text.match(/\[[\s\S]*\]/);
|
|
if (arrayMatch) {
|
|
return JSON.parse(arrayMatch[0]);
|
|
}
|
|
throw new Error("No JSON found in response");
|
|
}
|
|
};
|