parser.ts
3.42 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* Response parsing utilities for AI model outputs.
* Handles extraction of structured content from markdown-formatted responses.
*/
import { FileInfo } from '../types/file-types';
/**
* Extract JSON content from markdown code blocks
* Handles cases where AI models wrap JSON in ```json ... ``` or ``` ... ```
* If no code block markers are found, returns the original content
*
* @param response - Model response that may contain markdown code blocks
* @returns Extracted JSON string without markdown formatting
*
* @example
* // Input: "```json\n{\"key\": \"value\"}\n```"
* // Output: "{\"key\": \"value\"}"
*/
export function extractJSON(response: string): string {
// Try to match ```json ... ``` format first
const jsonBlockMatch = response.match(/```json\s*\n([\s\S]*?)\n```/);
if (jsonBlockMatch && jsonBlockMatch[1]) {
return jsonBlockMatch[1].trim();
}
// Try to match generic ``` ... ``` format (with newlines around content)
const codeBlockMatch = response.match(/```\s*\n([\s\S]*?)\n```/);
if (codeBlockMatch && codeBlockMatch[1]) {
return codeBlockMatch[1].trim();
}
// Fallback: no proper code block; use full content but strip loose markdown fences.
// Some models return raw JSON with trailing "```" (e.g. ...]```) or leading ```\n.
let cleaned = response.trim();
cleaned = cleaned.replace(/^\s*```(?:json)?\s*\n?/g, '').replace(/\s*```+\s*$/g, '');
return cleaned;
}
/**
* Extract code content from markdown code blocks
* Handles cases where AI models wrap code in ```tsx ... ``` or ``` ... ```
* If no code block markers are found, returns the original content
*/
export function extractCode(response: string): string {
// 1. Try to extract content strictly within ``` fences
// Regex captures content between ```language and ```
const codeBlockMatch = response.match(/```(?:tsx|typescript|react|js|javascript|json|css|less|scss)?\s*\n([\s\S]*?)```/);
if (codeBlockMatch && codeBlockMatch[1]) {
return codeBlockMatch[1].trim();
}
// 2. Fallback: If no clear block structure is found (or fences are missing/malformed),
// try to strip loose fences just in case, but usually method 1 catches the block.
// If the model returned JUST code without fences, this preserves it.
// If the model returned "Here is code: code", this returns the whole string (which might be bad, but safest fallback).
// Removing loose fences if any remain (unlikely if method 1 failed but good for cleanup)
const cleaned = response
.replace(/```(tsx|typescript|react|js|javascript|json|css|less|scss)?/g, '')
.replace(/```/g, '')
.trim();
return cleaned;
}
/**
* Extract multiple files from content with file headers
* Format:
* ## filename.tsx
* ```tsx
* code...
* ```
*
* ## filename.css
* ```css
* styles...
* ```
*/
export function extractFiles(content: string): FileInfo[] {
const files: FileInfo[] = [];
// Match file sections: ## filename\n```language\ncode\n```
// Allow optional whitespace around newlines for flexibility
const fileRegex = /##\s+([^\n]+)\s*\n\s*```(?:\w+)?\s*\n([\s\S]*?)\n\s*```/g;
let match;
while ((match = fileRegex.exec(content)) !== null) {
if (match[1] && match[2]) {
const filename = match[1].trim();
const code = match[2].trim();
files.push({ filename, content: code });
}
}
return files;
}