@pairdraw/mermaid 0.0.0-stage → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Danila Poyarkov and OpenPencil contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @pairdraw/mermaid
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Mermaid diagrams read into a typed model: flowcharts' nodes with their shapes and labels, edges with their arrowheads and strokes, subgraphs, and styles.
4
+
5
+ Parsing uses the grammar of a pinned Mermaid release, copied into `src/upstream` with the text preparation Mermaid runs before it by `bun run generate:mermaid-sources`, so it reads exactly what that release reads. The package does not depend on `@pairdraw/scene-graph`; laying diagrams out as design layers happens in `@pairdraw/core`.
@@ -0,0 +1,171 @@
1
+ import * as v from "valibot";
2
+ import { parse } from "yaml";
3
+ //#region src/upstream/comments.ts
4
+ /**
5
+ * Remove all lines starting with `%%` from the text that don't contain a `%%{`
6
+ * @param text - The text to remove comments from
7
+ * @returns cleaned text
8
+ */
9
+ const cleanupComments = (text) => {
10
+ return text.replace(/^\s*%%(?!{)[^\n]+\n?/gm, "").trimStart();
11
+ };
12
+ //#endregion
13
+ //#region src/upstream/regexes.ts
14
+ const directiveRegex = /%{2}{\s*(?:(\w+)\s*:|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi;
15
+ /** One character, tested against the same class `\s` means inside `anyCommentRegex`. */
16
+ const whitespace = /\s/;
17
+ /** True for the characters `[\n\r]` means in `frontMatterRegex`. */
18
+ const isLineBreak = (char) => char === "\n" || char === "\r";
19
+ /**
20
+ * Index of the last `[\n\r]` in the whitespace run starting at `from`, or `-1` if the run holds
21
+ * none. This is where a greedy `\s*[\n\r]+` stops: `\s*` takes the whole run, then gives
22
+ * characters back until the next one is a line break.
23
+ */
24
+ const lastLineBreakInWhitespaceRun = (text, from) => {
25
+ let index = -1;
26
+ for (let i = from; i < text.length && whitespace.test(text[i]); i++) if (isLineBreak(text[i])) index = i;
27
+ return index;
28
+ };
29
+ /**
30
+ * Locate a front matter block exactly like `text.match(frontMatterRegex)`, in linear time.
31
+ *
32
+ * A scanner rather than a regex, because `frontMatterRegex` is ambiguous: the opening `\s*[\n\r]`
33
+ * lets `\s*` consume line breaks as well, so every failed search for a closing fence backtracks
34
+ * into it. Each of the O(n) split points then rescans the lazy body, which is quadratic overall —
35
+ * on `'---\n' + ' \n'.repeat(n)`, well inside the default 50k `maxTextSize`:
36
+ *
37
+ * ```
38
+ * n = 4_000 38ms
39
+ * n = 8_000 161ms
40
+ * n = 16_000 619ms
41
+ * ```
42
+ *
43
+ * Removing the ambiguity is not behaviour-preserving, so the scanner reproduces the
44
+ * backtracking result rather than a tidier reading of it. The engine tries the *longest* opening
45
+ * first and shortens it one line break at a time until the rest matches, which is equivalent to:
46
+ *
47
+ * 1. Take the closing fences that could terminate a block — a line break, `indent---`, then at
48
+ * least one more line break in the following whitespace run.
49
+ * 2. The opening ends at the **last** line break of the run after `---` that still leaves a
50
+ * closing fence after it, since a longer opening is preferred but must leave one behind.
51
+ * 3. The body ends at the **first** closing fence after that, because the body is lazy.
52
+ *
53
+ * This is why `'---\n\n---\n\nMORE\n---\n'` is stripped whole: the opening swallows both leading
54
+ * line breaks, so the second `---` lands inside the body and only the third one can close.
55
+ *
56
+ * Two forward passes, each visiting a character a bounded number of times: the trailing
57
+ * whitespace runs of two closing fences cannot overlap, since `---` separates them.
58
+ */
59
+ const matchFrontMatter = (text) => {
60
+ let cursor = 0;
61
+ while (cursor < text.length && whitespace.test(text[cursor]) && !isLineBreak(text[cursor])) cursor++;
62
+ const indent = text.slice(0, cursor);
63
+ if (!text.startsWith("---", cursor)) return;
64
+ const openingEnds = [];
65
+ for (let i = cursor + 3; i < text.length && whitespace.test(text[i]); i++) if (isLineBreak(text[i])) openingEnds.push(i);
66
+ if (openingEnds.length === 0) return;
67
+ const closingFence = `${indent}---`;
68
+ const closingEnd = (i) => isLineBreak(text[i]) && text.startsWith(closingFence, i + 1) ? lastLineBreakInWhitespaceRun(text, i + 1 + closingFence.length) : -1;
69
+ const earliestBodyStart = openingEnds[0] + 1;
70
+ let lastClosingFence = -1;
71
+ for (let i = earliestBodyStart; i < text.length; i++) if (closingEnd(i) !== -1) lastClosingFence = i;
72
+ if (lastClosingFence === -1) return;
73
+ let openingEnd = openingEnds[0];
74
+ for (const candidate of openingEnds) if (candidate < lastClosingFence) openingEnd = candidate;
75
+ const bodyStart = openingEnd + 1;
76
+ for (let i = bodyStart; i <= lastClosingFence; i++) {
77
+ const matchEnd = closingEnd(i);
78
+ if (matchEnd !== -1) return {
79
+ indent,
80
+ body: text.slice(bodyStart, i),
81
+ length: matchEnd + 1
82
+ };
83
+ }
84
+ };
85
+ //#endregion
86
+ //#region src/upstream/preprocess.ts
87
+ const cleanupText = (code) => {
88
+ return code.replace(/\r\n?/g, "\n").replace(/<(\w+)([^>]*)>/g, (match, tag, attributes) => "<" + tag + attributes.replace(/="([^"]*)"/g, "='$1'") + ">");
89
+ };
90
+ const removeDirectives = function(text) {
91
+ return text.replace(directiveRegex, "");
92
+ };
93
+ /**
94
+ * @param text - text to be encoded
95
+ * @returns
96
+ */
97
+ const encodeEntities = function(text) {
98
+ let txt = text;
99
+ txt = txt.replace(/style.*:\S*#.*;/g, function(s) {
100
+ return s.substring(0, s.length - 1);
101
+ });
102
+ txt = txt.replace(/classDef.*:\S*#.*;/g, function(s) {
103
+ return s.substring(0, s.length - 1);
104
+ });
105
+ txt = txt.replace(/#\w+;/g, function(s) {
106
+ const innerTxt = s.substring(1, s.length - 1);
107
+ if (/^\+?\d+$/.test(innerTxt)) return "fl°°" + innerTxt + "¶ß";
108
+ else return "fl°" + innerTxt + "¶ß";
109
+ });
110
+ return txt;
111
+ };
112
+ /**
113
+ * Partially reverts encoding done via {@link encodeEntities}
114
+ *
115
+ * @param text - text to be decoded
116
+ * @returns
117
+ */
118
+ const decodeEntities = function(text) {
119
+ return text.replace(/fl°°/g, "&#").replace(/fl°/g, "&").replace(/¶ß/g, ";");
120
+ };
121
+ //#endregion
122
+ //#region src/source.ts
123
+ /** The front matter Pairdraw reads: the title, which YAML may give as a number or a flag. */
124
+ const frontMatterSchema = v.looseObject({ title: v.optional(v.pipe(v.union([
125
+ v.string(),
126
+ v.number(),
127
+ v.boolean()
128
+ ]), v.toString())) });
129
+ function frontMatterTitle(body) {
130
+ try {
131
+ const parsed = v.safeParse(frontMatterSchema, parse(body));
132
+ return parsed.success ? parsed.output.title : void 0;
133
+ } catch {
134
+ return;
135
+ }
136
+ }
137
+ /**
138
+ * Prepares Mermaid source as Mermaid does before its grammar reads it (`preprocessDiagram`, then
139
+ * `Diagram.fromText`), with the functions copied from the pinned release: line endings and HTML
140
+ * attributes cleaned up, front matter, directives, and comments taken out, and `#name;` entities
141
+ * hidden from the grammar, which reads `;` as a statement break.
142
+ */
143
+ function prepareSource(text) {
144
+ let code = cleanupText(text);
145
+ let title;
146
+ const frontMatter = matchFrontMatter(code);
147
+ if (frontMatter) {
148
+ const { indent } = frontMatter;
149
+ title = frontMatterTitle(indent ? frontMatter.body.split("\n").map((line) => line.startsWith(indent) ? line.slice(indent.length) : line).join("\n") : frontMatter.body);
150
+ code = code.slice(frontMatter.length);
151
+ }
152
+ return {
153
+ code: `${encodeEntities(cleanupComments(removeDirectives(code)))}\n`,
154
+ title
155
+ };
156
+ }
157
+ //#endregion
158
+ //#region src/detect.ts
159
+ /**
160
+ * The kind of Mermaid diagram `text` holds, by its first keyword after any front matter,
161
+ * directives, and comments, as Mermaid's detectors decide; null for a kind Pairdraw does not
162
+ * read, or text that is not Mermaid.
163
+ */
164
+ function detectMermaidDiagram(text) {
165
+ const { code } = prepareSource(text);
166
+ return /^\s*(?:graph|flowchart)\b/.test(code) ? "flowchart" : null;
167
+ }
168
+ //#endregion
169
+ export { decodeEntities, detectMermaidDiagram, prepareSource };
170
+
171
+ //# sourceMappingURL=detect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"detect.js","names":["parseYAML"],"sources":["../../src/upstream/comments.ts","../../src/upstream/regexes.ts","../../src/upstream/preprocess.ts","../../src/source.ts","../../src/detect.ts"],"sourcesContent":["// @ts-nocheck\n// Copied by `bun run generate:mermaid-sources` from mermaid@12.2.0\n// (https://raw.githubusercontent.com/mermaid-js/mermaid/1fb7869866dd619168d840291c9c54b4f129758b/packages/mermaid/src/diagram-api/comments.ts)\n// Copyright (c) 2014 - 2022 Knut Sveidqvist. MIT License; see MERMAID-LICENSE.txt.\n// Do not edit: change the pinned release in tools/generate/mermaid-sources and regenerate.\n/**\n * Remove all lines starting with `%%` from the text that don't contain a `%%{`\n * @param text - The text to remove comments from\n * @returns cleaned text\n */\nexport const cleanupComments = (text: string): string => {\n return text.replace(/^\\s*%%(?!{)[^\\n]+\\n?/gm, '').trimStart();\n};\n","// @ts-nocheck\n// Copied by `bun run generate:mermaid-sources` from mermaid@12.2.0\n// (https://raw.githubusercontent.com/mermaid-js/mermaid/1fb7869866dd619168d840291c9c54b4f129758b/packages/mermaid/src/diagram-api/regexes.ts)\n// Copyright (c) 2014 - 2022 Knut Sveidqvist. MIT License; see MERMAID-LICENSE.txt.\n// Do not edit: change the pinned release in tools/generate/mermaid-sources and regenerate.\n// Match Jekyll-style front matter blocks (https://jekyllrb.com/docs/front-matter/).\n// Based on regex used by Jekyll: https://github.com/jekyll/jekyll/blob/6dd3cc21c40b98054851846425af06c64f9fb466/lib/jekyll/document.rb#L10\n// Note that JS doesn't support the \"\\A\" anchor, which means we can't use\n// multiline mode.\n// Relevant YAML spec: https://yaml.org/spec/1.2.2/#914-explicit-documents\n// The \\1 backreference anchors closing `---` to the same indent as the opening one, guards against indented `---` inside multi-line YAML scalars (#7613).\n// Kept byte-for-byte as released: it is part of the published surface. It backtracks quadratically\n// (see `matchFrontMatter` below), so internal hot paths must use `matchFrontMatter` instead of\n// matching with this regex directly.\nexport const frontMatterRegex = /^([^\\S\\n\\r]*)-{3}\\s*[\\n\\r](.*?)[\\n\\r]\\1-{3}\\s*[\\n\\r]+/s;\n\nexport const directiveRegex =\n /%{2}{\\s*(?:(\\w+)\\s*:|(\\w+))\\s*(?:(\\w+)|((?:(?!}%{2}).|\\r?\\n)*))?\\s*(?:}%{2})?/gi;\n\n// Kept byte-for-byte as released: it is part of the published surface, and consumers replace with\n// `'\\n'` — a pattern change (capture groups, lookbehind) would silently change their output or throw\n// at module load on older engines. It backtracks quadratically on deep indents, so internal hot\n// paths must use `stripAnyComments` below instead of replacing with this regex directly.\nexport const anyCommentRegex = /\\s*%%.*\\n/gm;\n\n/** One character, tested against the same class `\\s` means inside `anyCommentRegex`. */\nconst whitespace = /\\s/;\n\n/**\n * Strip `%%` comment runs exactly like `text.replace(anyCommentRegex, '\\n')`, in linear time.\n *\n * A scanner rather than a regex, because no variant of this pattern is linear. Every regex form\n * carries a `\\s*` that can cross newlines, and `/m` gives the engine a candidate start at each\n * line, so an all-whitespace document has the match attempt rescan the remaining run once per\n * line. Two shapes are quadratic in the released pattern and in the guarded `(^|\\S)\\s*%%.*\\n`\n * that replaced it, both inside the default 50k `maxTextSize`:\n *\n * ```\n * ('\\n' + ' '.repeat(4)).repeat(10_000) all whitespace, many lines 256ms\n * '%%' + 'x%%'.repeat(16_000) no terminating newline 339ms\n * ```\n *\n * against 0.1ms for ordinary diagram text of the same size. The guard cut the constant roughly\n * 40x but left the exponent alone, which is what CodeQL and the CWE-1333 review both caught.\n *\n * The scan walks forward once. For each `%%` it takes the line's terminating newline as the end\n * of the match — `.` never matches a newline, so the regex ends at that same character — and\n * extends left over the preceding whitespace run, never past the previous match. Each character\n * is visited at most twice, so the work is linear in the input and independent of how the\n * whitespace is arranged.\n *\n * A `%%` with no newline after it is left alone, because `%%.*\\n` cannot match without one.\n */\nexport const stripAnyComments = (text: string): string => {\n let out = '';\n // Everything before this index has been emitted or dropped; also the floor for the leftward\n // whitespace scan, which is what `lastIndex` does for the global regex.\n let consumed = 0;\n let searchFrom = 0;\n\n while (searchFrom < text.length) {\n const marker = text.indexOf('%%', searchFrom);\n if (marker === -1) {\n break;\n }\n const lineEnd = text.indexOf('\\n', marker);\n if (lineEnd === -1) {\n // No newline left in the string, so this `%%` and every later one cannot match.\n break;\n }\n let start = marker;\n while (start > consumed && whitespace.test(text[start - 1])) {\n start--;\n }\n out += text.slice(consumed, start) + '\\n';\n consumed = lineEnd + 1;\n searchFrom = consumed;\n }\n\n return out + text.slice(consumed);\n};\n\n/** True for the characters `[\\n\\r]` means in `frontMatterRegex`. */\nconst isLineBreak = (char: string | undefined): boolean => char === '\\n' || char === '\\r';\n\n/**\n * Index of the last `[\\n\\r]` in the whitespace run starting at `from`, or `-1` if the run holds\n * none. This is where a greedy `\\s*[\\n\\r]+` stops: `\\s*` takes the whole run, then gives\n * characters back until the next one is a line break.\n */\nconst lastLineBreakInWhitespaceRun = (text: string, from: number): number => {\n let index = -1;\n for (let i = from; i < text.length && whitespace.test(text[i]); i++) {\n if (isLineBreak(text[i])) {\n index = i;\n }\n }\n return index;\n};\n\nexport interface FrontMatterMatch {\n /** The horizontal indent of the opening fence — `frontMatterRegex`'s capture group 1. */\n indent: string;\n /** The YAML body between the fences — capture group 2. */\n body: string;\n /** Length of the whole match, so callers can slice the front matter off. */\n length: number;\n}\n\n/**\n * Locate a front matter block exactly like `text.match(frontMatterRegex)`, in linear time.\n *\n * A scanner rather than a regex, because `frontMatterRegex` is ambiguous: the opening `\\s*[\\n\\r]`\n * lets `\\s*` consume line breaks as well, so every failed search for a closing fence backtracks\n * into it. Each of the O(n) split points then rescans the lazy body, which is quadratic overall —\n * on `'---\\n' + ' \\n'.repeat(n)`, well inside the default 50k `maxTextSize`:\n *\n * ```\n * n = 4_000 38ms\n * n = 8_000 161ms\n * n = 16_000 619ms\n * ```\n *\n * Removing the ambiguity is not behaviour-preserving, so the scanner reproduces the\n * backtracking result rather than a tidier reading of it. The engine tries the *longest* opening\n * first and shortens it one line break at a time until the rest matches, which is equivalent to:\n *\n * 1. Take the closing fences that could terminate a block — a line break, `indent---`, then at\n * least one more line break in the following whitespace run.\n * 2. The opening ends at the **last** line break of the run after `---` that still leaves a\n * closing fence after it, since a longer opening is preferred but must leave one behind.\n * 3. The body ends at the **first** closing fence after that, because the body is lazy.\n *\n * This is why `'---\\n\\n---\\n\\nMORE\\n---\\n'` is stripped whole: the opening swallows both leading\n * line breaks, so the second `---` lands inside the body and only the third one can close.\n *\n * Two forward passes, each visiting a character a bounded number of times: the trailing\n * whitespace runs of two closing fences cannot overlap, since `---` separates them.\n */\nexport const matchFrontMatter = (text: string): FrontMatterMatch | undefined => {\n let cursor = 0;\n while (cursor < text.length && whitespace.test(text[cursor]) && !isLineBreak(text[cursor])) {\n cursor++;\n }\n const indent = text.slice(0, cursor);\n\n if (!text.startsWith('---', cursor)) {\n return undefined;\n }\n\n // Candidate opening ends: the line breaks of the whitespace run after the opening `---`.\n const openingEnds: number[] = [];\n for (let i = cursor + 3; i < text.length && whitespace.test(text[i]); i++) {\n if (isLineBreak(text[i])) {\n openingEnds.push(i);\n }\n }\n if (openingEnds.length === 0) {\n return undefined;\n }\n\n const closingFence = `${indent}---`;\n // A closing fence is only usable if the trailing `\\s*[\\n\\r]+` matches too.\n const closingEnd = (i: number): number =>\n isLineBreak(text[i]) && text.startsWith(closingFence, i + 1)\n ? lastLineBreakInWhitespaceRun(text, i + 1 + closingFence.length)\n : -1;\n\n const earliestBodyStart = openingEnds[0] + 1;\n\n let lastClosingFence = -1;\n for (let i = earliestBodyStart; i < text.length; i++) {\n if (closingEnd(i) !== -1) {\n lastClosingFence = i;\n }\n }\n if (lastClosingFence === -1) {\n return undefined;\n }\n\n // Longest opening that still leaves a closing fence behind. One always exists: every closing\n // fence sits at or after `earliestBodyStart`, which is past `openingEnds[0]`.\n let openingEnd = openingEnds[0];\n for (const candidate of openingEnds) {\n if (candidate < lastClosingFence) {\n openingEnd = candidate;\n }\n }\n\n const bodyStart = openingEnd + 1;\n for (let i = bodyStart; i <= lastClosingFence; i++) {\n const matchEnd = closingEnd(i);\n if (matchEnd !== -1) {\n return { indent, body: text.slice(bodyStart, i), length: matchEnd + 1 };\n }\n }\n\n return undefined;\n};\n","// @ts-nocheck\n// Copied by `bun run generate:mermaid-sources` from mermaid@12.2.0\n// (https://raw.githubusercontent.com/mermaid-js/mermaid/1fb7869866dd619168d840291c9c54b4f129758b/packages/mermaid/src/preprocess.ts)\n// (https://raw.githubusercontent.com/mermaid-js/mermaid/1fb7869866dd619168d840291c9c54b4f129758b/packages/mermaid/src/utils.ts)\n// Copyright (c) 2014 - 2022 Knut Sveidqvist. MIT License; see MERMAID-LICENSE.txt.\n// Do not edit: change the pinned release in tools/generate/mermaid-sources and regenerate.\nimport { directiveRegex } from './regexes'\n\nexport const cleanupText = (code: string) => {\n return (\n code\n // parser problems on CRLF ignore all CR and leave LF;;\n .replace(/\\r\\n?/g, '\\n')\n // clean up html tags so that all attributes use single quotes, parser throws error on double quotes\n .replace(\n /<(\\w+)([^>]*)>/g,\n (match, tag, attributes) => '<' + tag + attributes.replace(/=\"([^\"]*)\"/g, \"='$1'\") + '>'\n )\n );\n};\n\nexport const removeDirectives = function (text: string): string {\n return text.replace(directiveRegex, '');\n};\n\n/**\n * @param text - text to be encoded\n * @returns\n */\nexport const encodeEntities = function (text: string): string {\n let txt = text;\n\n txt = txt.replace(/style.*:\\S*#.*;/g, function (s): string {\n return s.substring(0, s.length - 1);\n });\n txt = txt.replace(/classDef.*:\\S*#.*;/g, function (s): string {\n return s.substring(0, s.length - 1);\n });\n\n txt = txt.replace(/#\\w+;/g, function (s) {\n const innerTxt = s.substring(1, s.length - 1);\n\n const isInt = /^\\+?\\d+$/.test(innerTxt);\n if (isInt) {\n return 'fl°°' + innerTxt + '¶ß';\n } else {\n return 'fl°' + innerTxt + '¶ß';\n }\n });\n\n return txt;\n};\n\n/**\n * Partially reverts encoding done via {@link encodeEntities}\n *\n * @param text - text to be decoded\n * @returns\n */\nexport const decodeEntities = function (text: string): string {\n return text.replace(/fl°°/g, '&#').replace(/fl°/g, '&').replace(/¶ß/g, ';');\n};\n","import * as v from 'valibot'\nimport { parse as parseYAML } from 'yaml'\n\nimport { cleanupComments } from './upstream/comments'\nimport { cleanupText, encodeEntities, removeDirectives } from './upstream/preprocess'\nimport { matchFrontMatter } from './upstream/regexes'\n\n/** Mermaid source as a diagram's grammar reads it, and the title its front matter gives. */\nexport interface PreparedSource {\n code: string\n title?: string\n}\n\n/** The front matter Pairdraw reads: the title, which YAML may give as a number or a flag. */\nconst frontMatterSchema = v.looseObject({\n title: v.optional(v.pipe(v.union([v.string(), v.number(), v.boolean()]), v.toString()))\n})\n\nfunction frontMatterTitle(body: string): string | undefined {\n try {\n const parsed = v.safeParse(frontMatterSchema, parseYAML(body))\n return parsed.success ? parsed.output.title : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Prepares Mermaid source as Mermaid does before its grammar reads it (`preprocessDiagram`, then\n * `Diagram.fromText`), with the functions copied from the pinned release: line endings and HTML\n * attributes cleaned up, front matter, directives, and comments taken out, and `#name;` entities\n * hidden from the grammar, which reads `;` as a statement break.\n */\nexport function prepareSource(text: string): PreparedSource {\n let code = cleanupText(text)\n let title: string | undefined\n const frontMatter = matchFrontMatter(code)\n if (frontMatter) {\n // Mermaid dedents front matter by its fences' indent before reading it.\n const { indent } = frontMatter\n const body = indent\n ? frontMatter.body\n .split('\\n')\n .map((line) => (line.startsWith(indent) ? line.slice(indent.length) : line))\n .join('\\n')\n : frontMatter.body\n title = frontMatterTitle(body)\n code = code.slice(frontMatter.length)\n }\n return { code: `${encodeEntities(cleanupComments(removeDirectives(code)))}\\n`, title }\n}\n","import { prepareSource } from './source'\n\n/** The Mermaid diagrams Pairdraw reads. */\nexport type MermaidDiagramType = 'flowchart'\n\n/**\n * The kind of Mermaid diagram `text` holds, by its first keyword after any front matter,\n * directives, and comments, as Mermaid's detectors decide; null for a kind Pairdraw does not\n * read, or text that is not Mermaid.\n */\nexport function detectMermaidDiagram(text: string): MermaidDiagramType | null {\n const { code } = prepareSource(text)\n return /^\\s*(?:graph|flowchart)\\b/.test(code) ? 'flowchart' : null\n}\n"],"mappings":";;;;;;;;AAUA,MAAa,mBAAmB,SAAyB;CACvD,OAAO,KAAK,QAAQ,0BAA0B,EAAE,CAAC,CAAC,UAAU;AAC9D;;;ACIA,MAAa,iBACX;;AASF,MAAM,aAAa;;AAyDnB,MAAM,eAAe,SAAsC,SAAS,QAAQ,SAAS;;;;;;AAOrF,MAAM,gCAAgC,MAAc,SAAyB;CAC3E,IAAI,QAAQ;CACZ,KAAK,IAAI,IAAI,MAAM,IAAI,KAAK,UAAU,WAAW,KAAK,KAAK,EAAE,GAAG,KAC9D,IAAI,YAAY,KAAK,EAAE,GACrB,QAAQ;CAGZ,OAAO;AACT;;;;;;;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