'use strict'; const fs = require('fs'); const tmp = require('tmp'); const { spawnSync } = require('node:child_process'); function mermaid(config) { return function(args, content) { let options = Object.assign({}, config); let caption = '', configPath = ''; args.forEach(arg => { const arr = arg.split(':'); if (arr.length == 1) { caption = arr; } else { const [ key, val ] = arr; options[key] = val; } }); let mmdcArgs = [ '-t', options.theme, '-w', options.width, '-H', options.height, '-e', options.format, '-b', options.background, '-s', options.scale, '-i', '-', '-o', '-' ]; const arr = content.split(''); if (arr.length == 2) { const mmdConfig = arr[0]; content = arr[1]; const tmpFile = tmp.fileSync(); configPath = tmpFile.name; fs.writeFileSync(configPath, mmdConfig); } if (configPath !== '') { mmdcArgs.push('-c', configPath); } const result = spawnSync(options.mmdcPath, mmdcArgs, { cwd: process.cwd(), env: process.env, input: content, encoding: 'utf8', timeout: options.timeout }); if (result.status === 0) { if (result.stderr) { console.warn(result.stderr); } const path = 'data:image/svg+xml;base64,' + Buffer.from(result.stdout).toString('base64'); if (caption != '') { return `
${ caption }
${ caption }
` } else { return `

`; } } if (result.error) { throw result.error; } throw Error('mmdc exited with code ' + result.status + (result.stderr ? ': ' + result.stderr : '.')); }; } module.exports = mermaid;