Skip to content

Commit

Permalink
perf: skip launching puppeteer when not needed
Browse files Browse the repository at this point in the history
Skip launching puppeteer until it's actually needed.

Running mermaid-cli on a markdown file without any mermaid code blocks
shouldn't launch puppeteer, if it's unnecessary.

Fix: #694
  • Loading branch information
aloisklink committed Jun 1, 2024
1 parent f23637d commit 6de2f96
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,11 @@ async function run (input, output, { puppeteerConfig = {}, quiet = false, output
// TODO: should we use a Markdown parser like remark instead of rolling our own parser?
const mermaidChartsInMarkdown = /^[^\S\n]*[`:]{3}(?:mermaid)([^\S\n]*\r?\n([\s\S]*?))[`:]{3}[^\S\n]*$/
const mermaidChartsInMarkdownRegexGlobal = new RegExp(mermaidChartsInMarkdown, 'gm')
const browser = await puppeteer.launch(puppeteerConfig)
/**
* @type {puppeteer.Browser | undefined}
* Lazy-loaded browser instance, only created when needed.
*/
let browser
try {
if (!outputFormat) {
const outputFormatFromFilename =
Expand All @@ -435,6 +439,9 @@ async function run (input, output, { puppeteerConfig = {}, quiet = false, output
if (input && /\.(md|markdown)$/.test(input)) {
const imagePromises = []
for (const mermaidCodeblockMatch of definition.matchAll(mermaidChartsInMarkdownRegexGlobal)) {
if (browser === undefined) {
browser = await puppeteer.launch(puppeteerConfig)
}
const mermaidDefinition = mermaidCodeblockMatch[2]

/** Output can be either a template image file, or a `.md` output file.
Expand Down Expand Up @@ -488,11 +495,12 @@ async function run (input, output, { puppeteerConfig = {}, quiet = false, output
}
} else {
info('Generating single mermaid chart')
browser = await puppeteer.launch(puppeteerConfig)
const data = await parseMMD(browser, definition, outputFormat, parseMMDOptions)
await fs.promises.writeFile(output, data)
}
} finally {
await browser.close()
await browser?.close?.()
}
}

Expand Down
3 changes: 3 additions & 0 deletions test-positive/mermaidless-markdown-file.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# This markdown file has no mermaid code blocks in it

This markdown file purposely has no mermaid code blocks in it.

0 comments on commit 6de2f96

Please sign in to comment.