diff --git a/lib/mdx-utils.ts b/lib/mdx-utils.ts index 4f3ee4c0..3a9bad25 100644 --- a/lib/mdx-utils.ts +++ b/lib/mdx-utils.ts @@ -7,14 +7,36 @@ export function fixMdxDataProps(content: string): string { let endIndex = -1; const startObj = dataIndex + 6; // index of the first '{' in 'data={{' + let inString = false; + let isEscaped = false; + for (let i = startObj; i < fixedContent.length; i++) { - if (fixedContent[i] === '{') { - openCount++; - } else if (fixedContent[i] === '}') { - openCount--; - if (openCount === 0) { - endIndex = i; - break; + const char = fixedContent[i]; + + if (isEscaped) { + isEscaped = false; + continue; + } + + if (char === '\\') { + isEscaped = true; + continue; + } + + if (char === '"') { + inString = !inString; + continue; + } + + if (!inString) { + if (char === '{') { + openCount++; + } else if (char === '}') { + openCount--; + if (openCount === 0) { + endIndex = i; + break; + } } } } diff --git a/package.json b/package.json index 35752595..4ed96370 100644 --- a/package.json +++ b/package.json @@ -116,7 +116,7 @@ "prepare": "husky", "preinstall": "npx only-allow pnpm" }, - "version": "2.3.30", + "version": "2.3.31", "pnpm": { "onlyBuiltDependencies": [ "@parcel/watcher", diff --git a/tests/mdx-regex.test.ts b/tests/mdx-regex.test.ts index 9262a21c..a4ff4fc9 100644 --- a/tests/mdx-regex.test.ts +++ b/tests/mdx-regex.test.ts @@ -8,10 +8,15 @@ describe('MDX Data Props Fixer', () => { const result = fixMdxDataProps(mdxInput); - // The expected output should have the entire JSON object enclosed in data="{...}" - // and NO trailing characters left over from the regex truncating early. const expected = ``; expect(result).toBe(expected); }); + + it('should not prematurely truncate if } appears inside a string literal', () => { + const mdxInput = `"}}} />`; + const result = fixMdxDataProps(mdxInput); + const expected = ``; + expect(result).toBe(expected.replace('>', '>')); + }); });