diff --git a/packages/docusaurus-plugin-openapi-docs/src/markdown/utils.test.ts b/packages/docusaurus-plugin-openapi-docs/src/markdown/utils.test.ts new file mode 100644 index 000000000..9882741df --- /dev/null +++ b/packages/docusaurus-plugin-openapi-docs/src/markdown/utils.test.ts @@ -0,0 +1,26 @@ +/* ============================================================================ + * Copyright (c) Palo Alto Networks + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * ========================================================================== */ + +import { clean } from "./utils"; + +describe("clean", () => { + it("escapes curly brackets outside code", () => { + expect( + clean("Use {value}, `const value = {}`, and ~removed~ {text}.") + ).toBe("Use \\{value\\}, `const value = {}`, and ~removed~ \\{text\\}."); + }); + + it.each([ + ["backtick", '```json\n{\n "ok": true\n}\n```'], + ["tilde", '~~~json\n{\n "ok": true\n}\n~~~'], + ])("preserves %s fenced code blocks", (_name, codeBlock) => { + const input = `Before {value}\n${codeBlock}\nAfter {value}`; + const expected = `Before \\{value\\}\n${codeBlock}\nAfter \\{value\\}`; + + expect(clean(input)).toBe(expected); + }); +}); diff --git a/packages/docusaurus-plugin-openapi-docs/src/markdown/utils.ts b/packages/docusaurus-plugin-openapi-docs/src/markdown/utils.ts index 966070b92..8efca7760 100644 --- a/packages/docusaurus-plugin-openapi-docs/src/markdown/utils.ts +++ b/packages/docusaurus-plugin-openapi-docs/src/markdown/utils.ts @@ -218,24 +218,26 @@ export const greaterThan = /(?/gu; export const codeFence = /`{1,3}[\s\S]*?`{1,3}/g; export const curlyBrackets = /([{}])/g; -export const codeBlock = /(^```.*[\s\S]*?```$|`[^`].+?`)/gm; +export const codeBlock = /(^```.*[\s\S]*?```$|^~~~.*[\s\S]*?~~~$|`[^`].+?`)/gm; export function clean(value: string | undefined): string { if (!value) { return ""; } - let sections = value.split(codeBlock); - for (let sectionIndex in sections) { - if (!sections[sectionIndex].startsWith("`")) { - sections[sectionIndex] = sections[sectionIndex] - .replace(lessThan, "<") - .replace(greaterThan, ">") - .replace(codeFence, function (match) { - return match.replace(/\\>/g, ">"); - }) - .replace(curlyBrackets, "\\$1"); - } + const sections = value.split(codeBlock); + for ( + let sectionIndex = 0; + sectionIndex < sections.length; + sectionIndex += 2 + ) { + sections[sectionIndex] = sections[sectionIndex] + .replace(lessThan, "<") + .replace(greaterThan, ">") + .replace(codeFence, function (match) { + return match.replace(/\\>/g, ">"); + }) + .replace(curlyBrackets, "\\$1"); } return sections.join(""); }