(sectionText: string)
| 103 | } |
| 104 | |
| 105 | export function splitOutCodeChunks(sectionText: string): string[] { |
| 106 | const chunks: string[] = []; |
| 107 | const codeBlockPattern = /```(\w*)\n([\s\S]+?)```/g; |
| 108 | // (\w*) to capture the language abbreviation |
| 109 | // [\s\S]+? to capture the code content (non-greedy) |
| 110 | // [\s\S] includes newlines |
| 111 | let match; |
| 112 | |
| 113 | // Find initial index for cutting the string |
| 114 | let currentIndex = 0; |
| 115 | |
| 116 | while ((match = codeBlockPattern.exec(sectionText))) { |
| 117 | const nonCodeChunk = sectionText.slice(currentIndex, match.index); |
| 118 | |
| 119 | // If there is any non-code text between two code blocks |
| 120 | if (nonCodeChunk.trim().length !== 0) { |
| 121 | chunks.push(nonCodeChunk); |
| 122 | } |
| 123 | |
| 124 | const languageAbbrev = match[1] ?? ""; |
| 125 | // Extract code content from a code block, trim additional redundant spaces |
| 126 | let codeChunk = match[2].trim(); |
| 127 | if (isJson(codeChunk)) { |
| 128 | const jsonChunk = getPossibleJsonChunk(codeChunk); |
| 129 | // If the code chunk is JSON, reduce tokens by removing unnecessary prettification |
| 130 | const prePost = codeChunk.split(jsonChunk); |
| 131 | |
| 132 | // Nothing to do if first line or not found (-1) |
| 133 | codeChunk = prePost[0] + unprettifyJsonString(jsonChunk) + prePost[1]; |
| 134 | } |
| 135 | |
| 136 | // Re-add the code block markdown formatting, so it's obvious it's a code block |
| 137 | chunks.push(`\`\`\`${languageAbbrev}\n${codeChunk}\n\`\`\``); |
| 138 | |
| 139 | // Move to the end of the current match |
| 140 | currentIndex = codeBlockPattern.lastIndex; |
| 141 | } |
| 142 | |
| 143 | // If there is a non-code section after the last code block |
| 144 | if (currentIndex < sectionText.length - 1) { |
| 145 | const finalChunk = sectionText.slice(currentIndex).trim(); |
| 146 | if (finalChunk.length !== 0) { |
| 147 | chunks.push(finalChunk); |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | return chunks; |
| 152 | } |
| 153 | |
| 154 | export function getPossibleJsonChunk(text: string): string { |
| 155 | // Regex to check if text contains [] or {} |
no test coverage detected