Skip to content

feat: artefacts option #868

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jun 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ node_modules/
yarn-error.log
test-positive/*.out.md
test-output/
static-out/

# these are no longer used, but may still be in people's git folders
fontawesome/
Expand Down
15 changes: 9 additions & 6 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,18 @@ Please note that this project is released with a [Contributor Code of Conduct][c
## Submitting a pull request

1. [Fork][fork] and clone the repository
1. Configure and install the dependencies: `npm install`
1. Create a new branch: `git checkout -b my-branch-name`. Make sure to give a good name to the branch. New features shall start with `feature/<branch name>`. Bug fixes shall start with `fix/<branch-name>`
1. Make your change, add tests, and make sure the tests still pass
1. Push to your fork and [submit a pull request][pr]
1. Give yourself a high five, and wait for your pull request to be reviewed and merged.
2. Configure and install the dependencies: `npm install`
3. Create a new branch: `git checkout -b my-branch-name`. Make sure to give a good name to the branch. New features shall start with `feature/<branch name>`. Bug fixes shall start with `fix/<branch-name>`
4. Make your change, add tests, and make sure the tests still pass - including
1. Unit tests (`npm test`)
2. E2E tests (`npm run test:cli`)
5. Push to your fork and [submit a pull request][pr]
6. Give yourself a high five, and wait for your pull request to be reviewed and merged.

Here are a few things you can do that will increase the likelihood of your pull request is accepted:

- Follow the [style guide][style] which is using [standard][style]. Any linting errors should be shown when running `npm test`.
- Some linting errors might be automatically fixed by `npm run lint-fix`.
- Some linting errors might be automatically fixed by `npm run lint-fix`.
- Write and update tests.
- Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, submit them as separate pull requests.
- Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).
Expand All @@ -33,3 +35,4 @@ Work in the Progress pull requests are also welcome to get feedback early on, or
- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
- [Using Pull Requests](https://help.github.com/articles/about-pull-requests/)
- [GitHub Help](https://help.github.com)

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"prepare": "tsc && vite build",
"prepack": "tsc && vite build",
"test": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" npx jest",
"test:cli": "bash run-tests.sh test-positive",
"version": "node scripts/version.js",
"lint": "standard",
"lint-fix": "standard --fix"
Expand Down
33 changes: 33 additions & 0 deletions run-tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ IMAGETAG=$2

set -e

# If no image tag is provided, build the Docker image
if [ -z "$IMAGETAG" ]; then
echo "No image tag provided, building Docker image..."
# Get the current package version from package.json
VERSION=$(node -p "require('./package.json').version")
IMAGETAG="mermaid-cli:test"
docker build --build-arg VERSION=$VERSION -t $IMAGETAG -f DockerfileBuild .
fi

# we must set `useMaxWidth: false` in config` to convert-svg-to-png for Percy CI
config_noUseMaxWidth="$INPUT_DATA/config-noUseMaxWidth.json"

Expand Down Expand Up @@ -64,3 +73,27 @@ if grep -q "<br>" "./test-positive/graph-with-br.mmd.svg"; then
echo "<br> has not been replaced with <br/>";
exit 1;
fi

mkdir ./test-output/

# Run mmdc with --artefacts using existing test file
docker run --rm -v $(pwd):/data $IMAGETAG \
-i /data/test-positive/mermaid.md \
-o /data/test-output/mermaid-artefacts.md \
--artefacts /data/static-out/

# Verify that the images were created in the specified path
if [ ! -f "./static-out/mermaid-artefacts-1.svg" ]; then
echo "Images were not created in the specified artefact path";
exit 1;
fi

# Verify that the generated markdown file contains the correct image links
if ! grep -q "!\[diagram\](\.\/\.\.\/static-out\/mermaid-artefacts-1\.svg)" "./test-output/mermaid-artefacts.md"; then
echo "Generated markdown file does not contain the correct image links";
exit 1;
fi

# Clean up
rm -rf ./static-out/
rm -rf ./test-output/mermaid-artefacts.md
10 changes: 7 additions & 3 deletions src-test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -319,10 +319,14 @@ describe('mermaid-cli', () => {
})

describe("NodeJS API (import ... from '@mermaid-js/mermaid-cli')", () => {
beforeAll(async () => {
await fs.mkdir(join(out, './svg/dist/'), { recursive: true })
})

describe('run()', () => {
test('should write markdown output with svg images', async () => {
test.each([true, false])('should write markdown output with svg images - custom artefact path [%s]', async (artefact) => {
const expectedOutputMd = 'test-output/mermaid-run-output-test-svg.md'
const expectedOutputSvgs = [1, 2, 3].map((i) => `test-output/mermaid-run-output-test-svg-${i}.svg`)
const expectedOutputSvgs = [1, 2, 3].map((i) => `test-output${artefact ? '/svg/dist' : ''}/mermaid-run-output-test-svg-${i}.svg`)
// delete any files from previous test (fs.rm added in Node v14.14.0)
await Promise.all(
[
Expand All @@ -332,7 +336,7 @@ describe("NodeJS API (import ... from '@mermaid-js/mermaid-cli')", () => {
)

await run(
'test-positive/mermaid.md', expectedOutputMd, { quiet: true, outputFormat: 'svg' }
'test-positive/mermaid.md', expectedOutputMd, { quiet: true, outputFormat: 'svg', artefacts: artefact ? './test-output/svg/dist/' : undefined }
)

const markdownFile = await fs.readFile(expectedOutputMd, { encoding: 'utf8' })
Expand Down
25 changes: 21 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ async function cli () {
.addOption(new Option('-H, --height [height]', 'Height of the page').argParser(parseCommanderInt).default(600))
.option('-i, --input <input>', 'Input mermaid file. Files ending in .md will be treated as Markdown and all charts (e.g. ```mermaid (...)``` or :::mermaid (...):::) will be extracted and generated. Use `-` to read from stdin.')
.option('-o, --output [output]', 'Output file. It should be either md, svg, png, pdf or use `-` to output to stdout. Optional. Default: input + ".svg"')
.option('-a, --artefacts [artefacts]', 'Output artefacts path. Only used with Markdown input file. Optional. Default: output directory')
.addOption(new Option('-e, --outputFormat [format]', 'Output format for the generated image.').choices(['svg', 'png', 'pdf']).default(null, 'Loaded from the output file extension'))
.addOption(new Option('-b, --backgroundColor [backgroundColor]', 'Background color for pngs/svgs (not pdfs). Example: transparent, red, \'#F0F0F0\'.').default('white'))
.option('-c, --configFile [configFile]', 'JSON configuration file for mermaid.')
Expand All @@ -125,7 +126,7 @@ async function cli () {

const options = commander.opts()

let { theme, width, height, input, output, outputFormat, backgroundColor, configFile, cssFile, svgId, puppeteerConfigFile, scale, pdfFit, quiet, iconPacks } = options
let { theme, width, height, input, output, outputFormat, backgroundColor, configFile, cssFile, svgId, puppeteerConfigFile, scale, pdfFit, quiet, iconPacks, artefacts } = options

// check input file
if (!input) {
Expand Down Expand Up @@ -166,6 +167,15 @@ async function cli () {
error('Output file must end with ".md"/".markdown", ".svg", ".png" or ".pdf"')
}

if (artefacts) {
if (!input || !/\.(?:md|markdown)$/.test(input)) {
error('Artefacts [-a|--artefacts] path can only be used with Markdown input file')
}
if (!fs.existsSync(artefacts)) {
fs.mkdirSync(artefacts, { recursive: true })
}
}

const outputDir = path.dirname(output)
if (output !== '/dev/stdout' && !fs.existsSync(outputDir)) {
error(`Output directory "${outputDir}/" doesn't exist`)
Expand Down Expand Up @@ -207,7 +217,8 @@ async function cli () {
outputFormat,
parseMMDOptions: {
mermaidConfig, backgroundColor, myCSS, pdfFit, viewport: { width, height, deviceScaleFactor: scale }, svgId, iconPacks
}
},
artefacts
}
)
}
Expand Down Expand Up @@ -405,10 +416,11 @@ function markdownImage ({ url, title, alt }) {
* @param {import("puppeteer").LaunchOptions} [opts.puppeteerConfig] - Puppeteer launch options.
* @param {boolean} [opts.quiet] - If set, suppress log output.
* @param {"svg" | "png" | "pdf"} [opts.outputFormat] - Mermaid output format.
* @param {string} [opts.artefacts] - Path to the artefacts directory.
* Defaults to `output` extension. Overrides `output` extension if set.
* @param {ParseMDDOptions} [opts.parseMMDOptions] - Options to pass to {@link parseMMDOptions}.
*/
async function run (input, output, { puppeteerConfig = {}, quiet = false, outputFormat, parseMMDOptions } = {}) {
async function run (input, output, { puppeteerConfig = {}, quiet = false, outputFormat, parseMMDOptions, artefacts } = {}) {
/**
* Logs the given message to stdout, unless `quiet` is set to `true`.
*
Expand Down Expand Up @@ -465,10 +477,15 @@ async function run (input, output, { puppeteerConfig = {}, quiet = false, output
* I.e. if "out.md". use "out-1.svg", "out-2.svg", etc
* @type {string}
*/
const outputFile = output.replace(
let outputFile = output.replace(
/(\.(md|markdown|png|svg|pdf))$/,
`-${imagePromises.length + 1}$1`
).replace(/\.(md|markdown)$/, `.${outputFormat}`)

if (artefacts) {
outputFile = path.resolve(artefacts, path.basename(outputFile))
}

const outputFileRelative = `./${path.relative(path.dirname(path.resolve(output)), path.resolve(outputFile))}`

const imagePromise = (async () => {
Expand Down