Skip to content

Commit e4c9e4f

Browse files
committed
fix(cli): add safety fence decoration with newlines
1 parent 98e156f commit e4c9e4f

2 files changed

Lines changed: 26 additions & 13 deletions

File tree

.changeset/four-items-help.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"lingo.dev": patch
3+
---
4+
5+
add safety fence decoration with newlines

packages/cli/src/cli/loaders/mdx2/code-placeholder.ts

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
11
import { ILoader } from "../_types";
22
import { createLoader } from "../_utils";
3-
import { PlaceholderedMdx, RawMdx } from "./_types";
43
import { md5 } from "../../utils/md5";
5-
import { unified } from "unified";
6-
import remarkParse from "remark-parse";
7-
import remarkGfm from "remark-gfm";
8-
import { VFile } from "vfile";
9-
import remarkMdx from "remark-mdx";
4+
import _ from "lodash";
105

11-
function parseMdast(content: string) {
12-
const file = new VFile(content);
6+
const unindentedFenceRegex = /(?<!\n\n)```([\s\S]*?)```(?!\n\n)/g;
7+
const indentedFenceRegex = /```([\s\S]*?)```/g;
138

14-
const parser = unified().use(remarkParse).use(remarkGfm).use(remarkMdx);
9+
function ensureTrailingFenceNewline(_content: string) {
10+
let found = false;
11+
let content = _content;
1512

16-
const result = parser.parse(file);
13+
do {
14+
found = false;
15+
const matches = content.match(unindentedFenceRegex);
16+
if (matches) {
17+
const match = matches[0];
18+
content = content.replace(match, `\n\n${match}\n\n`);
19+
found = true;
20+
}
21+
} while (found);
1722

18-
return result;
23+
content = _.chain(content).split("\n\n").filter(Boolean).join("\n\n").value();
24+
25+
return content;
1926
}
2027

2128
// Helper that replaces code (block & inline) with stable placeholders and returns
@@ -27,10 +34,11 @@ function extractCodePlaceholders(content: string): {
2734
codePlaceholders: Record<string, string>;
2835
} {
2936
let finalContent = content;
37+
finalContent = ensureTrailingFenceNewline(finalContent);
38+
3039
const codePlaceholders: Record<string, string> = {};
3140

32-
const codeBlockRegex = /^```.*\n([\s\S]*?)^```$/gm;
33-
const codeBlockMatches = finalContent.matchAll(codeBlockRegex);
41+
const codeBlockMatches = finalContent.matchAll(indentedFenceRegex);
3442

3543
for (const match of codeBlockMatches) {
3644
const codeBlock = match[0];

0 commit comments

Comments
 (0)