diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml new file mode 100644 index 000000000..b87bbe090 --- /dev/null +++ b/.github/workflows/test.yaml @@ -0,0 +1,20 @@ +name: Test + +on: + push: + branches: [master, develop] + pull_request: + +permissions: + contents: read + +jobs: + mermaid: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + - name: Build the fixture site and check mermaid injection + run: node test/run.js diff --git a/_config.yml b/_config.yml index 815b498bc..637fdc957 100644 --- a/_config.yml +++ b/_config.yml @@ -754,15 +754,25 @@ post: # 流程图,基于 mermaid-js,具体请见:https://fluid.ist/docs/guide/#mermaid-流程图 # Flow chart, based on mermaid-js, see: https://fluid.ist/docs/en/guide/#mermaid mermaid: - # 开启后文章默认可用,自定义页面如需使用,需在 Front-matter 中指定 `mermaid: true` - # If you want to use mermaid on the custom page, you need to set `mermaid: true` in Front-matter + # 开启后文章默认可用;页面会自动检测正文中的 mermaid 图表(代码块、`{% mermaid %}` 标签、 + # `
`),一般无需再写 Front-matter。 + # 如果图表是运行时注入的(例如加密插件、动态加载的评论内容),或页面未引入 markdown 正文样式, + # 仍可在 Front-matter 中指定 `mermaid: true` 强制加载脚本。 + # Once enabled, posts work out of the box: the theme detects mermaid diagrams in the + # content (code fences, the `{% mermaid %}` tag and `
`), so the + # Front-matter flag is usually unnecessary. Set `mermaid: true` in Front-matter when + # diagrams are injected at runtime (encrypted posts, dynamically loaded content) or + # when the page does not include the markdown body styles. enable: false - # 开启后,只有在文章 Front-matter 里指定 `mermaid: true` 才会在文章页启动公式转换,以便在页面不包含公式时提高加载速度 - # If true, only set `mermaid: true` in Front-matter will enable mermaid, to load faster when the page does not contain mermaid + # 开启后,只有当页面包含 mermaid 图表或 Front-matter 指定 `mermaid: true` 时才加载脚本,以便在页面不包含图表时提高加载速度 + # 指定 `mermaid: false` 可强制关闭 + # If true, the script is only loaded when the page contains mermaid diagrams or `mermaid: true` is set in Front-matter, saving the load on pages without diagrams + # Set `mermaid: false` to opt out explicitly specific: false - # See: http://mermaid-js.github.io/mermaid/ + # 配置项与 mermaid 版本保持一致,可参考:https://mermaid.js.org/config/schema-docs/config.html + # Options follow the mermaid version schema, see: https://mermaid.js.org/config/schema-docs/config.html options: { theme: 'default' } # 评论插件 @@ -1136,7 +1146,7 @@ static_prefix: clipboard: https://lib.baomitu.com/clipboard.js/2.0.11/ - mermaid: https://lib.baomitu.com/mermaid/8.14.0/ + mermaid: https://cdn.jsdelivr.net/npm/mermaid@11.16.0/dist/ valine: https://lib.baomitu.com/valine/1.5.1/ diff --git a/layout/_partials/head.ejs b/layout/_partials/head.ejs index 648e06493..75292e00c 100644 --- a/layout/_partials/head.ejs +++ b/layout/_partials/head.ejs @@ -5,12 +5,20 @@ var keywords = page.keywords || config.keywords if (keywords instanceof Array) { keywords = keywords.join(',') } -var description = page.description || page.excerpt || (is_post() && page.content) || config.description +var description = page.description || page.excerpt || page.content || config.description if (description) { - description = strip_html(description).substring(0, 200).trim().replace(/\n/g, ' ') + // 先剥标签再去实体,避免 "&" 这类转义原样进入 meta 和 JSON-LD + // Strip tags first, then decode entities so escaped text stays readable in metadata + // 代码块内容不参与摘要,避免 meta 里出现整段源码 + // Code blocks never belong in a summary + description = unescape_html(strip_html(strip_mermaid(description).replace(//gi, ' '))).substring(0, 200).trim().replace(/\n/g, ' ') } -var ogImage = page.og_img || page.index_img -var ogConfig = Object.assign({ image: ogImage && url_for(ogImage) }, theme.open_graph) +// 正文首图优先于站点默认图,避免分享卡片千篇一律;只取绝对地址, +// 相对路径可能指向未提交的图片,分享卡片会从默认图退化成 404 +// Only absolute content images: a broken relative path would replace the default card with a 404 +var contentImage = ((page.content || '').match(/]*\ssrc=["']((?:https?:)?\/\/[^"']+)["']/i) || [])[1] +var ogImage = page.og_img || page.index_img || contentImage || theme.open_graph.image +var ogConfig = Object.assign({ description: description }, theme.open_graph, { image: ogImage && url_for(ogImage) }) %> @@ -35,6 +43,41 @@ var ogConfig = Object.assign({ image: ogImage && url_for(ogImage) }, theme.open_ <% } else { %> <% } %> + <% + // 结构化数据:文章输出 BlogPosting,首页输出 WebSite + // Structured data: BlogPosting for posts, WebSite for the home page + var jsonLd = null + var pageUrl = url_join(config.url, (page.canonical_path || page.path || '').replace('index.html', '')) + if (is_post()) { + jsonLd = { + '@context': 'https://schema.org', + '@type': 'BlogPosting', + headline: page.title, + description: description, + url: pageUrl, + mainEntityOfPage: { '@type': 'WebPage', '@id': pageUrl }, + author: { '@type': 'Person', name: page.author || config.author }, + publisher: { '@type': 'Organization', name: config.title }, + inLanguage: config.language + } + if (page.date) jsonLd.datePublished = page.date.toISOString() + if (page.updated || page.date) jsonLd.dateModified = (page.updated || page.date).toISOString() + if (ogConfig.image) jsonLd.image = full_url_for(ogConfig.image) + } else if (is_home() && page.current === 1) { + jsonLd = { + '@context': 'https://schema.org', + '@type': 'WebSite', + name: config.title, + url: config.url, + description: description, + inLanguage: config.language + } + if (ogConfig.image) jsonLd.image = full_url_for(ogConfig.image) + } + %> + <% if (jsonLd) { %> + <%- json_ld(jsonLd) %> + <% } %> <% if ((theme.post.meta.views.enable && theme.post.meta.views.source === 'busuanzi') || (theme.footer.statistics.enable && theme.footer.statistics.source === 'busuanzi')) { %> diff --git a/layout/_partials/markdown-plugins.ejs b/layout/_partials/markdown-plugins.ejs index e7a8272bb..370150b4d 100644 --- a/layout/_partials/markdown-plugins.ejs +++ b/layout/_partials/markdown-plugins.ejs @@ -19,6 +19,17 @@ <% if (theme.post.math.enable && (!theme.post.math.specific || (theme.post.math.specific && page.math))) { %> <%- partial('_partials/plugins/math.ejs') %> <% } %> -<% if (theme.post.mermaid.enable && (!theme.post.mermaid.specific || (theme.post.mermaid.specific && page.mermaid))) { %> +<% + // mermaid 块可能来自 ```mermaid 代码块、{% mermaid %} 标签,也可能是正文里的 + //
;检测到页面内确实存在图表元素时才加载脚本, + // 特定模式下无需再手动写 Front-matter。 + // Detect the elements mermaid will render, so that `specific: true` does not + // silently skip the script when the Front-matter flag is missing. + var hasMermaidBlock = has_mermaid(page.content || ''); + var needMermaid = theme.post.mermaid.enable + && page.mermaid !== false + && (!theme.post.mermaid.specific || page.mermaid || hasMermaidBlock); +%> +<% if (needMermaid) { %> <%- partial('_partials/plugins/mermaid.ejs') %> <% } %> diff --git a/layout/_partials/plugins/mermaid.ejs b/layout/_partials/plugins/mermaid.ejs index ffd2860e7..0e4a013ed 100644 --- a/layout/_partials/plugins/mermaid.ejs +++ b/layout/_partials/plugins/mermaid.ejs @@ -1,13 +1,36 @@ diff --git a/layout/index.ejs b/layout/index.ejs index a370e9c97..230bb430a 100644 --- a/layout/index.ejs +++ b/layout/index.ejs @@ -31,7 +31,7 @@ page.banner_mask_alpha = theme.index.banner_mask_alpha <% var excerpt = post.description || post.excerpt || (theme.index.auto_excerpt.enable && !post.encrypt && post.content) %>
- <%- strip_html(excerpt).substring(0, 200).trim().replace(/\n/g, ' ') %> + <%- strip_html(strip_mermaid(excerpt)).substring(0, 200).trim().replace(/\n/g, ' ') %>
diff --git a/scripts/events/index.js b/scripts/events/index.js index 84040b840..2049171bb 100644 --- a/scripts/events/index.js +++ b/scripts/events/index.js @@ -8,6 +8,7 @@ hexo.on('generateBefore', () => { require('./lib/compatible-configs')(hexo); require('./lib/injects')(hexo); require('./lib/highlight')(hexo); + require('./lib/mermaid')(hexo); require('./lib/lazyload')(hexo); require('./lib/footnote')(hexo); }); diff --git a/scripts/events/lib/highlight.js b/scripts/events/lib/highlight.js index 87d6c1500..4406298f0 100644 --- a/scripts/events/lib/highlight.js +++ b/scripts/events/lib/highlight.js @@ -14,6 +14,7 @@ try { const fs = require('fs'); const objUtil = require('../../utils/object'); const resolveModule = require('../../utils/resolve'); +const { hasMermaidCode, toMermaidClass } = require('../../utils/mermaid'); module.exports = (hexo) => { @@ -94,14 +95,14 @@ module.exports = (hexo) => { hexo.extend.filter.register('after_post_render', (page) => { if (hexo.config.highlight.line_number) { page.content = page.content.replace(/]+?highlight.+?]+?code[^>]+?>.*?().+?<\/figure>/gims, (str, p1) => { - if (/]+?mermaid[^>]+?>/ims.test(p1)) { + if (hasMermaidCode(p1)) { return p1.replace(/(class="[^>]*?)hljs([^>]*?")/gims, '$1$2').replace(/
/gims, '\n'); } return str; }); } else { page.content = page.content.replace(/(?)/gims, (str) => { - if (/]+?mermaid[^>]+?>/ims.test(str)) { + if (hasMermaidCode(str)) { return str.replace(/(class=".*?)hljs(.*?")/gims, '$1$2'); } return `
${str}
`; @@ -133,12 +134,11 @@ module.exports = (hexo) => { hexo.extend.filter.register('after_post_render', (page) => { page.content = page.content.replace(/(?)/gims, (str) => { - if (/]+?mermaid[^>]+?>/ims.test(str)) { + if (hasMermaidCode(str)) { if (hexo.config.highlight.line_number) { str = str.replace(/]+?line-numbers-rows[^>]+?>.+?<\/span><\/code>/, ''); } - str = str.replace(/]*?>/gims, '
')
-            .replace(/(class=".*?)language-mermaid(.*?")/gims, '$1mermaid$2')
+          str = toMermaidClass(str.replace(/]*?>/gims, '
'))
             .replace(/]+?>(.+?)<\/span>/gims, '$1');
           return str;
         }
diff --git a/scripts/events/lib/mermaid.js b/scripts/events/lib/mermaid.js
new file mode 100644
index 000000000..8a6ff85c1
--- /dev/null
+++ b/scripts/events/lib/mermaid.js
@@ -0,0 +1,24 @@
+/* global hexo */
+
+'use strict';
+
+const { hasMermaidElement } = require('../../utils/mermaid');
+
+module.exports = (hexo) => {
+  // 构建期提示:页面里有 mermaid 块,但配置导致脚本不会被加载时给出警告,
+  // 避免图表被当成普通文本静默展示
+  // Build-time warning: the page contains mermaid blocks but the script will not
+  // be loaded, so the diagrams would silently show up as plain text
+  hexo.extend.filter.register('after_post_render', (page) => {
+    const config = hexo.theme.config.post.mermaid;
+    if (!config || !hasMermaidElement(page.content || '')) {
+      return page;
+    }
+    if (!config.enable) {
+      hexo.log.warn(`[Fluid] Mermaid block found in "${page.path}" but "post.mermaid.enable" is false, it will be rendered as plain text.`);
+    } else if (page.mermaid === false) {
+      hexo.log.warn(`[Fluid] Mermaid block found in "${page.path}" but it is disabled by "mermaid: false" in Front-matter.`);
+    }
+    return page;
+  });
+};
diff --git a/scripts/helpers/mermaid.js b/scripts/helpers/mermaid.js
new file mode 100644
index 000000000..055dc5bdf
--- /dev/null
+++ b/scripts/helpers/mermaid.js
@@ -0,0 +1,9 @@
+/* global hexo */
+
+'use strict';
+
+const { hasMermaidElement } = require('../utils/mermaid');
+
+// EJS 模板里不能 require,检测逻辑通过 helper 暴露给 layout
+// EJS templates cannot require modules, so expose the detector as a helper
+hexo.extend.helper.register('has_mermaid', (content) => hasMermaidElement(content));
diff --git a/scripts/helpers/utils.js b/scripts/helpers/utils.js
index 7581d62e8..ba7327f49 100644
--- a/scripts/helpers/utils.js
+++ b/scripts/helpers/utils.js
@@ -3,7 +3,7 @@
 'use strict';
 
 const md5 = require('../utils/crypto');
-const { decodeURL } = require('hexo-util');
+const { decodeURL, unescapeHTML } = require('hexo-util');
 const compareVersions = require('../../scripts/utils/compare-versions');
 
 hexo.extend.helper.register('md5', function(string) {
@@ -27,3 +27,39 @@ hexo.extend.helper.register('deduplicate', function(arr) {
 });
 
 hexo.extend.helper.register('decode_url', decodeURL);
+
+// 移除正文里的 mermaid 源码,避免图表代码进入摘要和 meta description
+// Strip mermaid source so diagram code never leaks into excerpts or meta descriptions
+// 只匹配独立的 mermaid 类名,避免误伤 mermaid-wrapper 之类的复合类名;单双引号都支持
+// Match only the exact `mermaid` class token, so names like mermaid-wrapper survive
+const MERMAID_BLOCK = /<(pre|div|code)\b[^>]*\bclass=(["'])(?:[^"']*\s)?(?:language-)?mermaid(?:\s[^"']*)?\2[^>]*>[\s\S]*?<\/\1>/gi;
+
+hexo.extend.helper.register('strip_mermaid', function(html) {
+  // 第二步清掉只剩空壳的 
,fenced 代码块被剥离后会留下它
+  // Second pass removes the empty 
 left behind by a fenced block
+  return String(html || '').replace(MERMAID_BLOCK, ' ').replace(/]*>\s*<\/pre>/gi, ' ');
+});
+
+// 解码 HTML 实体,避免 "&" 原样出现在 meta description 和 JSON-LD 里
+// Decode HTML entities so escaped text does not leak into meta tags and JSON-LD
+hexo.extend.helper.register('unescape_html', function(value) {
+  // hexo-util 只覆盖少量实体,这里补上十进制数字实体(如 {)
+  // hexo-util covers only a few entities; decode decimal numerics as well
+  return unescapeHTML(String(value == null ? '' : value)).replace(/&#(\d+);/g, function(match, code) {
+    const n = Number(code);
+    if (!(n > 0 && n <= 0x10ffff) || (n >= 0xd800 && n <= 0xdfff)) {
+      return match;
+    }
+    return String.fromCodePoint(n);
+  });
+});
+
+// 输出 JSON-LD,转义 < 防止正文里的  提前闭合标签
+// Emit JSON-LD with < escaped so content cannot close the script tag early
+hexo.extend.helper.register('json_ld', function(data) {
+  if (!data) {
+    return '';
+  }
+  const json = JSON.stringify(data).replace(/${json}`;
+});
diff --git a/scripts/utils/mermaid.js b/scripts/utils/mermaid.js
new file mode 100644
index 000000000..f675e6f5e
--- /dev/null
+++ b/scripts/utils/mermaid.js
@@ -0,0 +1,107 @@
+'use strict';
+
+// 识别页面中真正会被 mermaid.run() 渲染的元素。
+// mermaid.run 默认按 `.mermaid` 选择器查找节点,所以这里必须基于真实的 class token,
+// 不能对整段 HTML 做宽松正则匹配:HTML 注释、', false, 'script body'],
+    ['', false, 'style body'],
+    ['<div class="mermaid">', false, 'escaped html'],
+    ['x', false, 'raw language- class is not rendered'],
+    ['
x
', false, 'not-mermaid class'], + ['
x
', false, 'prefixed class'], + ['just text', false, 'plain text'] + ]; + + for (const [html, expected, why] of elementCases) { + expectEqual(`hasMermaidElement(${why})`, hasMermaidElement(html), expected); + } + + // 代码块适配器需要识别 prism 转换前的 language-mermaid + // Adapters run before the class is rewritten, so accept language-mermaid there + expectEqual('hasMermaidCode(language-mermaid)', hasMermaidCode('x'), true); + expectEqual('hasMermaidCode(hljs mermaid)', hasMermaidCode('x'), true); + expectEqual('hasMermaidCode(not-mermaid)', hasMermaidCode('x'), false); + + const rewriteCases = [ + ['
x
', + '
x
', 'both wrapper and code'], + ['x', + 'x', 'other tokens preserved'], + ['x', + 'x', 'prefixed language untouched'], + ['x', + 'x', 'single quotes preserved'] + ]; + + for (const [html, expected, why] of rewriteCases) { + expectEqual(`toMermaidClass(${why})`, toMermaidClass(html), expected); + } +} + +function resolveModules() { + if (process.env.FLUID_TEST_MODULES) { + console.log(`[test] reusing node_modules from ${process.env.FLUID_TEST_MODULES}`); + return process.env.FLUID_TEST_MODULES; + } + const deps = path.join(WORK, 'deps'); + fs.mkdirSync(deps, { recursive: true }); + console.log('[test] installing dependencies...'); + // 固定版本:测试应该验证当前这套已知可用的组合,而不是随时漂移的 latest + // Pinned versions keep the test on the combination that was verified + const installed = spawnSync('npm', [ + 'install', '--no-save', '--no-audit', '--no-fund', '--loglevel=error', + 'hexo@8.1.2', 'hexo-renderer-ejs@2.0.0', 'hexo-renderer-marked@7.0.1', + 'hexo-renderer-stylus@3.0.1', 'hexo-pagination@3.0.0', 'nunjucks@3.2.4', + '@adobe/css-tools@4.3.3', 'hexo-prism-plugin@2.3.0' + ], { cwd: deps, stdio: 'inherit' }); + if (installed.status !== 0) { + fail('npm install failed'); + } + return path.join(deps, 'node_modules'); +} + +async function buildSite(name, fluidConfig, modules) { + const site = path.join(WORK, name); + copyDir(path.join(__dirname, 'fixture'), site); + copyDir(ROOT, path.join(site, 'themes', 'fluid')); + fs.writeFileSync(path.join(site, '_config.fluid.yml'), fluidConfig); + fs.symlinkSync(modules, path.join(site, 'node_modules'), 'dir'); + + const Hexo = require(path.join(site, 'node_modules', 'hexo')); + const hexo = new Hexo(site, { silent: true }); + const warnings = []; + await hexo.init(); + hexo.log.warn = (...args) => warnings.push(args.join(' ')); + hexo.log.info = () => {}; + hexo.log.debug = () => {}; + await hexo.call('generate'); + await hexo.exit(); + + return { + warnings, + html(page) { + const file = path.join(site, 'public', page, 'index.html'); + if (!fs.existsSync(file)) { + fail(`missing generated page ${page}/index.html in ${name}`); + } + return fs.readFileSync(file, 'utf8'); + } + }; +} + +function mermaidWarnings(warnings) { + return warnings.filter((line) => line.includes('[Fluid] Mermaid block found')); +} + +async function testEnabledBuild(modules) { + const site = await buildSite('enabled', ENABLED_CONFIG, modules); + + const cases = [ + { page: 'with-flag', loads: true, why: 'Front-matter mermaid: true' }, + { page: 'block-only', loads: true, why: '```mermaid fence' }, + { page: 'tag-only', loads: true, why: '{% mermaid %} tag' }, + { page: 'div-mermaid', loads: true, why: '
in content' }, + { page: 'plain', loads: false, why: 'no mermaid block' }, + { page: 'not-mermaid', loads: false, why: '```not-mermaid fence is not a diagram' }, + { page: 'escaped-sample', loads: false, why: 'mermaid example escaped inside an html fence' }, + { page: 'raw-language', loads: false, why: 'raw language-mermaid class is not rendered by run()' }, + { page: 'opt-out', loads: false, why: 'mermaid: false in Front-matter' } + ]; + + for (const item of cases) { + const html = site.html(item.page); + expectEqual(`${item.page}: mermaid.min.js`, html.includes('mermaid.min.js'), item.loads); + } + + const withFlag = site.html('with-flag'); + expectMatch('with-flag: startOnLoad forced off', withFlag, /Object\.assign\(\{\}, \{[^}]*\}, \{ startOnLoad: false \}\)/); + expectMatch('with-flag: theme options passed through', withFlag, /"theme":"forest"/); + expectNoMatch('with-flag: no legacy init()', withFlag, /mermaid\.init\s*\(/); + expectMatch('with-flag: querySelector explicit', withFlag, /querySelector:\s*['"]\.mermaid['"]/); + // suppressErrors 会吞掉 run() 的 reject,让失败无法观测 + // suppressErrors swallows run()'s rejection, hiding failures + expectMatch('with-flag: run() only passes querySelector', withFlag, /mermaid\.run\(\{\s*querySelector:\s*['"]\.mermaid['"]\s*\}\)/); + expectMatch('with-flag: load failures are reported', withFlag, /Failed to load mermaid/); + + // 代码块类名与高亮不能被误伤 + // Code blocks must keep their classes and highlighting + expectMatch('with-flag: mermaid code block preserved', withFlag, /class="[^"]*\bmermaid\b[^"]*"/); + const notMermaid = site.html('not-mermaid'); + expectMatch('not-mermaid: language class preserved', notMermaid, /class="[^"]*not-mermaid[^"]*"/); + expectMatch('not-mermaid: hljs class preserved', notMermaid, /class="hljs not-mermaid"/); + expectNoMatch('not-mermaid: no mermaid class rewrite', notMermaid, /class="mermaid"/); + + // 正文里的 div.mermaid 不能被代码块适配器包成 code-wrapper + // A raw div.mermaid must not be wrapped like a code block + const divMermaid = site.html('div-mermaid'); + expectMatch('div-mermaid: block preserved', divMermaid, /
/); + expectNoMatch('div-mermaid: not wrapped as code', divMermaid, /
/); + + // 代码围栏里的示例必须保持为高亮文本,不能变成真实图表节点 + // An escaped example must stay highlighted text, not become a diagram node + const escaped = site.html('escaped-sample'); + expectNoMatch('escaped-sample: no real mermaid element', escaped, /
/); + expectMatch('escaped-sample: kept as highlighted html', escaped, /class="hljs-tag"/); + + const found = mermaidWarnings(site.warnings); + expectEqual( + 'enabled: warnings only for the opted-out page', + found.map((line) => (line.includes('opt-out') ? 'opt-out' : line)).join(','), + 'opt-out' + ); +} + +async function testDisabledBuild(modules) { + const site = await buildSite('disabled', DISABLED_CONFIG, modules); + + for (const page of ['with-flag', 'block-only', 'tag-only', 'div-mermaid', 'opt-out', 'plain']) { + expectEqual(`disabled/${page}: mermaid.min.js`, site.html(page).includes('mermaid.min.js'), false); + } + + const found = mermaidWarnings(site.warnings); + const pagesWithWarning = found.map((line) => { + const match = line.match(/"([^"]+)"/); + return match ? match[1].split('/')[0] : line; + }).sort(); + expectEqual( + 'disabled: warns exactly for pages with renderable diagrams', + pagesWithWarning.join(','), + ['block-only', 'div-mermaid', 'opt-out', 'tag-only', 'with-flag'].join(',') + ); +} + +async function testHighlightLineNumberBuild(modules) { + const site = await buildSite('hljs-lineno', HLJS_LINENO_CONFIG, modules); + + const blockOnly = site.html('block-only'); + expectEqual('hljs+line_number/block-only: mermaid.min.js', blockOnly.includes('mermaid.min.js'), true); + expectMatch('hljs+line_number/block-only: figure unwrapped', blockOnly, /graph TD\n {2}A --> B\n<\/code>/); + expectNoMatch('hljs+line_number/block-only: figure removed', blockOnly, /
/); + expectMatch('hljs+line_number/not-mermaid: hljs class kept', notMermaid, /class="hljs not-mermaid"/); + expectMatch('hljs+line_number/not-mermaid: line numbers kept', notMermaid, /class="gutter"/); +} + +async function testPrismBuild(modules) { + const site = await buildSite('prism', PRISM_CONFIG, modules); + + const blockOnly = site.html('block-only'); + expectEqual('prism/block-only: mermaid.min.js', blockOnly.includes('mermaid.min.js'), true); + expectMatch('prism/block-only: language-mermaid rewritten', blockOnly, //); + expectNoMatch('prism/block-only: no leftover language class', blockOnly, /class="[^"]*language-mermaid[^"]*"/); + expectNoMatch('prism/block-only: line numbers removed', blockOnly, /line-numbers-rows/); + expectNoMatch('prism/block-only: pre attributes removed', blockOnly, /
/);
+
+  const divMermaid = site.html('div-mermaid');
+  expectEqual('prism/div-mermaid: mermaid.min.js', divMermaid.includes('mermaid.min.js'), true);
+
+  expectEqual('prism/plain: mermaid.min.js', site.html('plain').includes('mermaid.min.js'), false);
+}
+
+async function main() {
+  console.log(`[test] work dir: ${WORK}`);
+
+  testDetector();
+
+  const modules = resolveModules();
+  await testEnabledBuild(modules);
+  await testDisabledBuild(modules);
+  await testHighlightLineNumberBuild(modules);
+  await testPrismBuild(modules);
+
+  console.log('[test] all mermaid assertions passed');
+  fs.rmSync(WORK, { recursive: true, force: true });
+}
+
+main().catch((err) => {
+  fail(err && err.stack ? err.stack : String(err));
+});