AI-native design editor. Open-source Figma alternative.
feat: import Mermaid flowcharts as FigJam diagrams laid out by ELK (#1541)
Danila Poyarkov8277e7cf6994
diff --git a/.gitattributes b/.gitattributesindex 135363b1d..6f4ce94ab 100644--- a/.gitattributes+++ b/.gitattributes@@ -1,2 +1,4 @@tests/fixtures/*.fig filter=lfs diff=lfs merge=lfs -texttests/fixtures/fonts/*.ttf filter=lfs diff=lfs merge=lfs -text+# Copied and generated by tools/generate/mermaid-sources, whose checksums assume LF line endings.+packages/mermaid/src/upstream/** text eol=lfdiff --git a/.oxfmtrc.json b/.oxfmtrc.jsonindex 7a005ce58..a10448787 100644--- a/.oxfmtrc.json+++ b/.oxfmtrc.json@@ -1,5 +1,6 @@{"$schema": "./node_modules/oxfmt/configuration_schema.json",+ "ignorePatterns": ["packages/mermaid/src/upstream/"],"trailingComma": "none","tabWidth": 2,"semi": false,diff --git a/REUSE.toml b/REUSE.tomlindex b9986b62e..86fc32c10 100644--- a/REUSE.toml+++ b/REUSE.toml@@ -39,3 +39,18 @@ path = [precedence = "override"SPDX-FileCopyrightText = "2026 Danila Poyarkov and OpenPencil contributors"SPDX-License-Identifier = "MIT"++# Mermaid's flowchart grammar, the parser generated from it, and Mermaid's text preparation,+# copied from a pinned Mermaid release by tools/generate/mermaid-sources.+[[annotations]]+path = [+ "packages/mermaid/src/upstream/comments.ts",+ "packages/mermaid/src/upstream/flow.jison",+ "packages/mermaid/src/upstream/flow.js",+ "packages/mermaid/src/upstream/MERMAID-LICENSE.txt",+ "packages/mermaid/src/upstream/preprocess.ts",+ "packages/mermaid/src/upstream/regexes.ts",+]+precedence = "override"+SPDX-FileCopyrightText = "2014 - 2022 Knut Sveidqvist"+SPDX-License-Identifier = "MIT"diff --git a/bun.lock b/bun.lockindex aed6072c2..4efab7381 100644--- a/bun.lock+++ b/bun.lock@@ -41,6 +41,7 @@"@open-pencil/fig": "workspace:*","@open-pencil/harness": "workspace:*","@open-pencil/kiwi": "workspace:*",+ "@open-pencil/mermaid": "workspace:*","@open-pencil/pen": "workspace:*","@open-pencil/scene-graph": "workspace:*","@open-pencil/vue": "workspace:*",@@ -279,6 +280,7 @@"@open-pencil/drawio": "workspace:*","@open-pencil/fig": "workspace:*","@open-pencil/kiwi": "workspace:*",+ "@open-pencil/mermaid": "workspace:*","@open-pencil/pen": "workspace:*","@open-pencil/scene-graph": "workspace:*","@tauri-apps/api": "^2.12.1",@@ -289,6 +291,7 @@"culori": "^4.0.2","destr": "^2.0.5","diff": "^8.0.4",+ "elkjs": "^0.12.0","entities": "^8.0.0","es-toolkit": "^1.52.0","fflate": "^0.8.3",@@ -557,6 +560,21 @@"@types/ws": "^8.18.1",},},+ "packages/mermaid": {+ "name": "@open-pencil/mermaid",+ "version": "0.16.0",+ "dependencies": {+ "entities": "^8.0.0",+ "parse5": "^8.0.1",+ "valibot": "^1.5.0",+ "yaml": "^2.9.0",+ },+ "devDependencies": {+ "@types/bun": "^1.3.14",+ "tsdown": "^0.22.14",+ "typescript": "~5.8.3",+ },+ },"packages/pen": {"name": "@open-pencil/pen","version": "0.16.0",@@ -800,6 +818,17 @@"typescript": "~5.8.3",},},+ "tools/generate/mermaid-sources": {+ "name": "@open-pencil/mermaid-sources-tools",+ "dependencies": {+ "jison": "0.4.18",+ "typescript": "~5.8.3",+ },+ "devDependencies": {+ "@open-pencil/package-artifacts-tools": "workspace:*",+ "valibot": "^1.5.0",+ },+ },"tools/generate/tauri-menu": {"name": "@open-pencil/tauri-menu-tools","dependencies": {@@ -1680,6 +1709,10 @@"@open-pencil/mcp": ["@open-pencil/mcp@workspace:packages/mcp"],+ "@open-pencil/mermaid": ["@open-pencil/mermaid@workspace:packages/mermaid"],++ "@open-pencil/mermaid-sources-tools": ["@open-pencil/mermaid-sources-tools@workspace:tools/generate/mermaid-sources"],+"@open-pencil/navigation-benchmark-tools": ["@open-pencil/navigation-benchmark-tools@workspace:tools/dev/navigation-benchmark"],"@open-pencil/package-artifacts-tools": ["@open-pencil/package-artifacts-tools@workspace:tools/release/package-artifacts"],@@ -2714,6 +2747,10 @@"@zip.js/zip.js": ["@zip.js/[email protected]", "", {}, "sha512-Vr55wt21XKD0kZFCQEZOtbViUMUK/U0MH2MDsHxu6FSyYk3Wu+afh+f9xD01x0kerDNfHmUVrNpcgYAgtnRtjA=="],+ "JSONSelect": ["[email protected]", "", {}, "sha512-VRLR3Su35MH+XV2lrvh9O7qWoug/TUyj9tLDjn9rtpUCNnILLrHjgd/tB0KrhugCxUpj3UqoLqfYb3fLJdIQQQ=="],++ "JSV": ["[email protected]", "", {}, "sha512-ZJ6wx9xaKJ3yFUhq5/sk82PJMuUyLk277I8mQeyDgCTjGdjWJIvPfaU5LIXaMuaN2UO1X3kZH4+lgphublZUHw=="],+"abbrev": ["[email protected]", "", {}, "sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ=="],"abort-controller": ["[email protected]", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="],@@ -2738,6 +2775,8 @@"amaro": ["[email protected]", "", {}, "sha512-H1ReZZ8Te6HHaWAy9171A/iWkGZOusKCtdzmh6EnTgluiNiAV9OSmUIN5rZI1TZnw6+NAUNz+n6pAWoJAHhRIQ=="],+ "amdefine": ["[email protected]", "", {}, "sha512-S2Hw0TtNkMJhIabBwIojKL9YHO5T0n5eNqWJ7Lrlel/zDbftQpxpapi8tZs3X1HWa+u+QeydGmzzNU0m09+Rcg=="],+"ansi-colors": ["[email protected]", "", {}, "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw=="],"ansi-escapes": ["[email protected]", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg=="],@@ -2940,6 +2979,8 @@"cjs-module-lexer": ["[email protected]", "", {}, "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q=="],+ "cjson": ["[email protected]", "", { "dependencies": { "jsonlint": "1.6.0" } }, "sha512-bBRQcCIHzI1IVH59fR0bwGrFmi3Btb/JNwM/n401i1DnYgWndpsUBiQRAddLflkZage20A2d25OAWZZk0vBRlA=="],+"cli-highlight": ["[email protected]", "", { "dependencies": { "chalk": "^4.0.0", "highlight.js": "^10.7.1", "mz": "^2.4.0", "parse5": "^5.1.1", "parse5-htmlparser2-tree-adapter": "^6.0.0", "yargs": "^16.0.0" }, "bin": { "highlight": "bin/highlight" } }, "sha512-9KDcoEVwyUXrjcJNvHD0NFc/hiwe/WPVYIleQh2O1N2Zro5gWJZ/K+3DGn8w8P/F6FxOgzyC5bxDyHIgCSPhGg=="],"cli-table3": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0" }, "optionalDependencies": { "@colors/colors": "1.5.0" } }, "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ=="],@@ -3176,6 +3217,8 @@"easy-table": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" }, "optionalDependencies": { "wcwidth": "^1.0.1" } }, "sha512-OFzVOv03YpvtcWGe5AayU5G2hgybsg3iqA6drU8UaoZyB9jLGMTrz9+asnLp/E+6qPh88yEI1gvyZFZ41dmgww=="],+ "ebnf-parser": ["[email protected]", "", {}, "sha512-urvSxVQ6XJcoTpc+/x2pWhhuOX4aljCNQpwzw+ifZvV1andZkAmiJc3Rq1oGEAQmcjiLceyMXOy1l8ms8qs2fQ=="],+"ecdsa-sig-formatter": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="],"edge-paths": ["[email protected]", "", { "dependencies": { "@types/which": "^2.0.1", "which": "^2.0.2" } }, "sha512-sB7vSrDnFa4ezWQk9nZ/n0FdpdUuC6R1EOrlU3DL+bovcNFK28rqu2emmAUjujYEJTWIgQGqgVVWUZXMnc8iWg=="],@@ -3192,6 +3235,8 @@"electron-to-chromium": ["[email protected]", "", {}, "sha512-5lCAbyZBjtmUt/RAGHRqrL2q0oEFRThDAsZHHDn9XHa89Qw7gMYOeSicBTy+AHfvo0r6vwsZvqNJTQIQy1BLzA=="],+ "elkjs": ["[email protected]", "", {}, "sha512-YZcKynxVxYoKIOEpywEPwCFdg+BTbxQRNf3pbwdDCvc8O3kQD8bmIwSxKU1eOTVc4Xo+VG9Te+575mlfvOrhEQ=="],+"emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],"emoji-regex-xs": ["[email protected]", "", {}, "sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg=="],@@ -3242,7 +3287,7 @@"escape-string-regexp": ["[email protected]", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],- "escodegen": ["[email protected]", "", { "dependencies": { "esprima": "^4.0.1", "estraverse": "^5.2.0", "esutils": "^2.0.2" }, "optionalDependencies": { "source-map": "~0.6.1" }, "bin": { "esgenerate": "bin/esgenerate.js", "escodegen": "bin/escodegen.js" } }, "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w=="],+ "escodegen": ["[email protected]", "", { "dependencies": { "esprima": "~1.1.1", "estraverse": "~1.5.0", "esutils": "~1.0.0" }, "optionalDependencies": { "source-map": "~0.1.33" }, "bin": { "esgenerate": "./bin/esgenerate.js", "escodegen": "./bin/escodegen.js" } }, "sha512-z9FWgKc48wjMlpzF5ymKS1AF8OIgnKLp9VyN7KbdtyrP/9lndwUFqCtMm+TAJmJf7KJFFYc4cFJfVTTGkKEwsA=="],"eslint": ["[email protected]", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.2", "@eslint/config-array": "^0.23.5", "@eslint/config-helpers": "^0.7.0", "@eslint/core": "^1.2.1", "@eslint/plugin-kit": "^0.7.2", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", "ajv": "^6.14.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", "eslint-scope": "^9.1.2", "eslint-visitor-keys": "^5.0.1", "espree": "^11.2.0", "esquery": "^1.7.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", "minimatch": "^10.2.5", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, "peerDependencies": { "jiti": "*" }, "optionalPeers": ["jiti"], "bin": { "eslint": "bin/eslint.js" } }, "sha512-9VaAkDURekixUQJy0oJYl2DcN6oKMfxay7XzaGYAWQwsb6qfKf+x76R2k1L8kb1boc+FyCAaTA9GmiKaaiaF+A=="],@@ -3256,7 +3301,7 @@"espree": ["[email protected]", "", { "dependencies": { "acorn": "^8.16.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^5.0.1" } }, "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw=="],- "esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],+ "esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-qxxB994/7NtERxgXdFgLHIs9M6bhLXc6qtUmWZ3L8+gTQ9qaoyki2887P2IqAYsoENyr8SUbTutStDniOHSDHg=="],"esquery": ["[email protected]", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g=="],@@ -3264,7 +3309,7 @@"esrecurse": ["[email protected]", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="],- "estraverse": ["[email protected]", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],+ "estraverse": ["[email protected]", "", {}, "sha512-FpCjJDfmo3vsc/1zKSeqR5k42tcIhxFIlvq+h9j0fO2q/h2uLKyweq7rYJ+0CoVvrGQOxIS5wyBrW/+vF58BUQ=="],"estree-walker": ["[email protected]", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],@@ -3690,6 +3735,10 @@"jest-util": ["[email protected]", "", { "dependencies": { "@jest/types": "30.4.1", "@types/node": "*", "chalk": "^4.1.2", "ci-info": "^4.2.0", "graceful-fs": "^4.2.11", "picomatch": "^4.0.3" } }, "sha512-vjQb1sACEiv13DKJMDToJpzVW0joCsIQrmbg0fi7CyOOt+g9jTuQl2A216pWRBYhOVt53XbL/2LbMKg1BECWOw=="],+ "jison": ["[email protected]", "", { "dependencies": { "JSONSelect": "0.4.0", "cjson": "0.3.0", "ebnf-parser": "0.1.10", "escodegen": "1.3.x", "esprima": "1.1.x", "jison-lex": "0.3.x", "lex-parser": "~0.1.3", "nomnom": "1.5.2" }, "bin": { "jison": "lib/cli.js" } }, "sha512-FKkCiJvozgC7VTHhMJ00a0/IApSxhlGsFIshLW6trWJ8ONX2TQJBBz6DlcO1Gffy4w9LT+uL+PA+CVnUSJMF7w=="],++ "jison-lex": ["[email protected]", "", { "dependencies": { "lex-parser": "0.1.x", "nomnom": "1.5.2" }, "bin": { "jison-lex": "cli.js" } }, "sha512-EBh5wrXhls1cUwROd5DcDHR1sG7CdsCFSqY1027+YA1RGxz+BX2TDLAhdsQf40YEtFDGoiO0Qm8PpnBl2EzDJw=="],+"jiti": ["[email protected]", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="],"jose": ["[email protected]", "", {}, "sha512-XrchZOFZUl/T3vTwRe8XK+cJrGtMF4th1ARnDfwbBXFKThGhlsxEE4Zu03AD/bjJSt/9jT/mxrOCkJWOg77aPA=="],@@ -3738,6 +3787,8 @@"jsonfile": ["[email protected]", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="],+ "jsonlint": ["[email protected]", "", { "dependencies": { "JSV": ">= 4.0.x", "nomnom": ">= 1.5.x" }, "bin": { "jsonlint": "lib/cli.js" } }, "sha512-x6YLBe6NjdpmIeiklwQOxsZuYj/SOWkT33GlTpaG1UdFGjdWjPcxJ1CWZAX3wA7tarz8E2YHF6KiW5HTapPlXw=="],+"jsonpointer": ["[email protected]", "", {}, "sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ=="],"jspdf": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.28.6", "fast-png": "^6.2.0", "fflate": "^0.8.1" }, "optionalDependencies": { "canvg": "^3.0.11", "core-js": "^3.6.0", "dompurify": "^3.3.1", "html2canvas": "^1.0.0-rc.5" } }, "sha512-YyAXyvnmjTbR4bHQRLzex3CuINCDlQnBqoSYyjJwTP2x9jDLuKDzy7aKUl0hgx3uhcl7xzg32agn5vlie6HIlQ=="],@@ -3774,6 +3825,8 @@"levn": ["[email protected]", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="],+ "lex-parser": ["[email protected]", "", {}, "sha512-DuAEISsr1H4LOpmFLkyMc8YStiRWZCO8hMsoXAXSbgyfvs2WQhSt0+/FBv3ZU/JBFZMGcE+FWzEBSzwUU7U27w=="],+"lib0": ["[email protected]", "", { "dependencies": { "isomorphic.js": "^0.2.4" }, "bin": { "0serve": "bin/0serve.js", "0gentesthtml": "bin/gentesthtml.js", "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js" } }, "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw=="],"lie": ["[email protected]", "", { "dependencies": { "immediate": "~3.0.5" } }, "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ=="],@@ -4052,6 +4105,8 @@"nodemailer": ["[email protected]", "", {}, "sha512-izw9mVKFix6YSnC9eLgV6g1opl9DUlRio9ZNcq+Wu9Ujn2UwF+8Nl0B8nz22kEC+CTZCvinkxwJ0DeFbb6NwcQ=="],+ "nomnom": ["[email protected]", "", { "dependencies": { "colors": "0.5.x", "underscore": "1.1.x" } }, "sha512-fiVbT7BqxiQqjlR9U3FDGOSERFCKoXVCdxV2FwZuNN7/cmJ42iQx35nUFOAFDcyvemu9Adp+IlsCGlKQYLmBKw=="],+"nopt": ["[email protected]", "", { "dependencies": { "abbrev": "^2.0.0" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w=="],"normalize-package-data": ["[email protected]", "", { "dependencies": { "hosted-git-info": "^8.0.0", "semver": "^7.3.5", "validate-npm-package-license": "^3.0.4" } }, "sha512-linxNAT6M0ebEYZOx2tO6vBEFsVgnPpv+AVjk0wJHfaUIbq31Jm3T6vvZaarnOeWDh8ShnwXuaAyM7WT3RzErA=="],@@ -4832,6 +4887,8 @@"unconfig-core": ["[email protected]", "", { "dependencies": { "@quansync/fs": "^1.0.0", "quansync": "^1.0.0" } }, "sha512-Su3FauozOGP44ZmKdHy2oE6LPjk51M/TRRjHv2HNCWiDvfvCoxC2lno6jevMA91MYAdCdwP05QnWdWpSbncX/w=="],+ "underscore": ["[email protected]", "", {}, "sha512-w4QtCHoLBXw1mjofIDoMyexaEdWGMedWNDhlWTtT1V1lCRqi65Pnoygkh6+WRdr+Bm8ldkBNkNeCsXGMlQS9HQ=="],+"undici": ["[email protected]", "", {}, "sha512-aWZpUj7XoGonMClx4gdDRfgBjqeA+F473aDmROQQbM9n6PRfK/u1q/a0X4wMTgcHfT8H6fpbt98PFuDUwFg2YA=="],"undici-types": ["[email protected]", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],@@ -5424,6 +5481,12 @@"degenerator/ast-types": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w=="],+ "degenerator/escodegen": ["[email protected]", "", { "dependencies": { "esprima": "^4.0.1", "estraverse": "^5.2.0", "esutils": "^2.0.2" }, "optionalDependencies": { "source-map": "~0.6.1" }, "bin": { "esgenerate": "bin/esgenerate.js", "escodegen": "bin/escodegen.js" } }, "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w=="],++ "degenerator/esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],++ "detective-amd/escodegen": ["[email protected]", "", { "dependencies": { "esprima": "^4.0.1", "estraverse": "^5.2.0", "esutils": "^2.0.2" }, "optionalDependencies": { "source-map": "~0.6.1" }, "bin": { "esgenerate": "bin/esgenerate.js", "escodegen": "bin/escodegen.js" } }, "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w=="],+"detective-typescript/@typescript-eslint/typescript-estree": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/project-service": "8.67.0", "@typescript-eslint/tsconfig-utils": "8.67.0", "@typescript-eslint/types": "8.67.0", "@typescript-eslint/visitor-keys": "8.67.0", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-EKQBCE9yNlRJYm7jdTW5AhDacDUmSwQb0FAJAmK2EKYrNXIsa2vxcSZx6PvJ/dEdI6lS+Y9W+EXckLj0iPFGcw=="],"dom-serializer/entities": ["[email protected]", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],@@ -5436,10 +5499,20 @@"editorconfig/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="],+ "escodegen/esutils": ["[email protected]", "", {}, "sha512-x/iYH53X3quDwfHRz4y8rn4XcEwwCJeWsul9pF1zldMbGtgOtMNBEOuYWwB1EQlK2LRa1fev3YAgym/RElp5Cg=="],++ "escodegen/source-map": ["[email protected]", "", { "dependencies": { "amdefine": ">=0.0.4" } }, "sha512-VtCvB9SIQhk3aF6h+N85EaqIaBFIAfZ9Cu+NJHHVvc8BbEcnvDcFw6sqQ2dQrT6SlOrZq3tIvyD9+EGq/lJryQ=="],+"eslint/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="],+ "eslint-scope/estraverse": ["[email protected]", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],+"espree/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="],+ "esquery/estraverse": ["[email protected]", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],++ "esrecurse/estraverse": ["[email protected]", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],+"execa/@sindresorhus/merge-streams": ["@sindresorhus/[email protected]", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="],"execa/signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],@@ -5538,6 +5611,8 @@"node-fetch/data-uri-to-buffer": ["[email protected]", "", {}, "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="],+ "nomnom/colors": ["[email protected]", "", {}, "sha512-XjsuUwpDeY98+yz959OlUK6m7mLBM+1MEG5oaenfuQnNnrQk1WvtcvFgN3FNDP3f2NmZ211t0mNEfSEN1h0eIg=="],+"normalize-package-data/hosted-git-info": ["[email protected]", "", { "dependencies": { "lru-cache": "^10.0.1" } }, "sha512-Rw/B2DNQaPBICNXEm8balFz9a6WpZrkCGpcWFpy7nCj+NyhSdqXipmfvtmWt9xGfp0wZnBxB+iVpLmQMYt47Tw=="],"npm-run-path/path-key": ["[email protected]", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="],@@ -5586,6 +5661,8 @@"readdir-glob/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="],+ "recast/esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],+"recursive-readdir/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],"resq/fast-deep-equal": ["[email protected]", "", {}, "sha512-bCK/2Z4zLidyB4ReuIsvALH6w31YfAQDmXMqMx6FyfHqvBxtjC0eRumeSu4Bs3XtXwpyIywtSTrVT99BxY1f9w=="],@@ -6028,6 +6105,12 @@"d3-time/d3-array/internmap": ["[email protected]", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],+ "degenerator/escodegen/estraverse": ["[email protected]", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],++ "detective-amd/escodegen/esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],++ "detective-amd/escodegen/estraverse": ["[email protected]", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],+"detective-typescript/@typescript-eslint/typescript-estree/@typescript-eslint/project-service": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.67.0", "@typescript-eslint/types": "^8.67.0", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-cvE8c7ulYeXN9fYuszhCeCsbzyVEXuhrRCybnBre7TUmqb5nRmBfQAwCj0O3WJFDeyAZt4VYv51vMCC9LHSdYw=="],"detective-typescript/@typescript-eslint/typescript-estree/@typescript-eslint/tsconfig-utils": ["@typescript-eslint/[email protected]", "", { "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-vV+LUSv5njUWsknE71fqKTlXUva+R76SaeORd6Zojcunk/6DvKFXONU3BrAs2H49mbygUXt6gbYunzwqNwlhdg=="],@@ -6050,6 +6133,8 @@"gray-matter/js-yaml/argparse": ["[email protected]", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="],+ "gray-matter/js-yaml/esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],+"jszip/readable-stream/string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],"lazystream/readable-stream/string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],diff --git a/changes/1541/added.md b/changes/1541/added.mdnew file mode 100644index 000000000..6f0c0d5d8--- /dev/null+++ b/changes/1541/added.md@@ -0,0 +1 @@+- Mermaid flowcharts open from `.mmd` and `.mermaid` files and paste onto the canvas as FigJam shapes, sections, and connectors laid out automatically, keeping their shapes, arrowheads, line styles, labels, and `classDef`/`style` colours; AI and MCP agents import them with `import_mermaid`.diff --git a/desktop/src/launch/args.rs b/desktop/src/launch/args.rsindex 12d2cee02..87ba80ed1 100644--- a/desktop/src/launch/args.rs+++ b/desktop/src/launch/args.rs@@ -8,7 +8,7 @@ pub fn file_association_path(path: PathBuf) -> Option<PathBuf> {return None;}let ext = path.extension()?.to_string_lossy().to_lowercase();- matches!(ext.as_str(), "fig" | "pen" | "drawio" | "dio").then_some(path)+ matches!(ext.as_str(), "fig" | "pen" | "drawio" | "dio" | "mmd" | "mermaid").then_some(path)}fn path_from_arg(arg: String, cwd: &Path) -> Option<PathBuf> {diff --git a/desktop/tauri.conf.json b/desktop/tauri.conf.jsonindex 00931134d..d4406bac7 100644--- a/desktop/tauri.conf.json+++ b/desktop/tauri.conf.json@@ -57,6 +57,14 @@"role": "Editor","mimeType": "application/vnd.jgraph.mxfile","rank": "Alternate"+ },+ {+ "ext": ["mmd", "mermaid"],+ "name": "Mermaid Diagram",+ "description": "Mermaid diagram",+ "role": "Viewer",+ "mimeType": "text/vnd.mermaid",+ "rank": "Alternate"}],"linux": {diff --git a/oxlint.json b/oxlint.jsonindex 7149829ce..455e3f24c 100644--- a/oxlint.json+++ b/oxlint.json@@ -630,6 +630,7 @@"node_modules","dist","desktop",+ "packages/mermaid/src/upstream","*.config.*"],"categories": {diff --git a/package.json b/package.jsonindex 66e00fe2d..62963d06a 100644--- a/package.json+++ b/package.json@@ -7,6 +7,7 @@"packages/scene-graph","packages/pen","packages/drawio",+ "packages/mermaid","packages/kiwi","packages/fig","packages/core",@@ -43,6 +44,7 @@"tools/generate/demo","tools/generate/emoji-metrics","tools/generate/landing-posters",+ "tools/generate/mermaid-sources","tools/generate/tauri-menu","tools/generate/visual-oracles","tools/release/package-artifacts",@@ -64,9 +66,9 @@"build:native-test": "bun run generate:icons --target desktop && bun run build:packages && bun tauri build --debug --no-bundle --features native-test --config desktop/tauri.native-test.conf.json","benchmark:navigation": "bun tools/dev/navigation-benchmark/src/cli.ts run","test:native": "bun run build:native-test && wdio run wdio.conf.ts",- "lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/feedback/src/ packages/cloud/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/emit/src/ packages/kiwi/src/ packages/fig/src/ packages/drawio/src/ packages/docs/.vitepress/theme/landing/",- "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",- "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/",+ "lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/feedback/src/ packages/cloud/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/emit/src/ packages/kiwi/src/ packages/fig/src/ packages/drawio/src/ packages/mermaid/src/ packages/docs/.vitepress/theme/landing/",+ "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/mermaid/src/ packages/mermaid/tests/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/ packages/docs/.vitepress/theme/landing/",+ "format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/mcp/tests/ packages/harness/src/ packages/harness/tests/ packages/feedback/src/ packages/feedback/tests/ packages/cloud/src/ packages/cloud/tests/ packages/cloud/deploy/ packages/cloud/tsdown.config.ts packages/cloud/tsdown.standalone.config.ts packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/pen/src/ packages/pen/tests/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/emit/src/ packages/emit/tests/ packages/kiwi/src/ packages/kiwi/tests/ packages/fig/src/ packages/fig/tests/ packages/drawio/src/ packages/drawio/tests/ packages/mermaid/src/ packages/mermaid/tests/ tests scripts/ tools/ packages/docs/.vitepress/theme/landing/","format:check": "bun run format && status=$(git status --porcelain -uall) && test -z \"$status\" || (echo \"$status\" && exit 1)","check": "bun run check:icons && bun run build:packages && bun run lint && tsgo --noEmit && bun run check:vue && bun run check:native-test && bun run check:i18n && bun run check:docs && bun run check:changelog && bun run check:packages && bun run check:deps && bun run check:audit && bun run check:secrets && bun run check:monorepo && bun run check:arch && bun run check:test-homes && bun run check:cloud-off && bun run check:test-types && bun run test:type-shapes && bun run check:tools && bun run test:tools && bun run test:dupes","check:commits": "commitlint",@@ -113,6 +115,7 @@"docs:preview": "bun --filter @open-pencil/docs preview","generate:demo": "bun tools/generate/demo/src/cli.ts --force","generate:emoji-metrics": "bun tools/generate/emoji-metrics/src/generate.ts",+ "generate:mermaid-sources": "bun tools/generate/mermaid-sources/src/generate.ts","generate:landing-posters": "bun tools/generate/landing-posters/src/generate.ts --force","generate:icons": "bun tools/generate/brand/src/cli.ts generate","check:icons": "bun tools/generate/brand/src/cli.ts check",@@ -156,6 +159,7 @@"@open-pencil/fig": "workspace:*","@open-pencil/harness": "workspace:*","@open-pencil/kiwi": "workspace:*",+ "@open-pencil/mermaid": "workspace:*","@open-pencil/pen": "workspace:*","@open-pencil/scene-graph": "workspace:*","@open-pencil/vue": "workspace:*",diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.tsindex e268bee26..52d14f58b 100644--- a/packages/cli/src/headless.ts+++ b/packages/cli/src/headless.ts@@ -39,6 +39,9 @@ function documentAssetReader(filePath: string) {export async function loadDocument(filePath: string): Promise<SceneGraph> {const bytes = new Uint8Array(await readFile(filePath))+ // A format laid out as it is read places its layers by their text's size, which is measured+ // as an export draws it rather than estimated.+ if (io.findReader(filePath)?.laysOutOnRead) await measureTextHeadlessly()const { graph } = await io.readDocument({name: filePath,data: bytes,diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdindex 970347536..41a058331 100644--- a/packages/core/AGENTS.md+++ b/packages/core/AGENTS.md@@ -16,6 +16,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do- `@open-pencil/yoga-layout` supplies both flexbox and CSS Grid.- Recompute layout after demo creation and for each materialized or imported page; scope computation to the affected page or subtree where possible.- The first Hug/Fill dimension mutation switches only that axis to Fixed; focus is non-destructive, and mode/value changes share one undo transaction.+- Diagrams of nodes, groups, and edges lay out in `packages/core/src/layout/diagram/`: `layoutDiagram` runs ELK, loaded on first use, and `applyDiagramLayout` moves the layers that draw it and runs their connectors along its routes; importers and tools that arrange diagrams go through them, and connectors that pass through stored bend points use `bendConnectorThrough` (`packages/core/tests/layout/diagram/apply.test.ts`).- A shape with text fits itself to its label before its auto layout runs: it grows from its given size only while the label needs room, and layout never changes that given size (`packages/core/tests/layout/generated/shape-with-text.test.ts`).## Components and instancesdiff --git a/packages/core/package.json b/packages/core/package.jsonindex c4100f69c..bd50295d6 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -183,6 +183,7 @@"@open-pencil/drawio": "workspace:*","@open-pencil/fig": "workspace:*","@open-pencil/kiwi": "workspace:*",+ "@open-pencil/mermaid": "workspace:*","@open-pencil/pen": "workspace:*","@open-pencil/scene-graph": "workspace:*","@tauri-apps/api": "^2.12.1",@@ -193,6 +194,7 @@"culori": "^4.0.2","destr": "^2.0.5","diff": "^8.0.4",+ "elkjs": "^0.12.0","entities": "^8.0.0","es-toolkit": "^1.52.0","fflate": "^0.8.3",diff --git a/packages/core/src/editor/bridges/clipboard.ts b/packages/core/src/editor/bridges/clipboard.tsindex 743051b7b..3a332edcd 100644--- a/packages/core/src/editor/bridges/clipboard.ts+++ b/packages/core/src/editor/bridges/clipboard.ts@@ -18,6 +18,7 @@ export function createClipboardBridge(clipboard: ClipboardActions, selection: SeplaceFiles: clipboard.placeFiles,placeImageFiles: clipboard.placeImageFiles,pasteSVG: clipboard.pasteSVG,+ pasteMermaid: clipboard.pasteMermaid,loadFontsForNodes: clipboard.loadFontsForNodes,copySelectionAsText: clipboard.copySelectionAsText,copySelectionAsSVG: clipboard.copySelectionAsSVG,diff --git a/packages/core/src/editor/clipboard/assets.ts b/packages/core/src/editor/clipboard/assets.tsindex e7e628996..818d482fd 100644--- a/packages/core/src/editor/clipboard/assets.ts+++ b/packages/core/src/editor/clipboard/assets.ts@@ -192,6 +192,27 @@ export function createClipboardAssetActions(return placeAssets([asset], cx, cy, 'Paste SVG')}+ /**+ * Paste a Mermaid flowchart as FigJam shapes, sections, and connectors, laid out and centred on+ * the point; false when the text is not one.+ */+ async function pasteMermaid(text: string, cx: number, cy: number): Promise<boolean> {+ const { detectMermaidDiagram, parseFlowchart } = await import('@open-pencil/mermaid')+ if (!detectMermaidDiagram(text)) return false+ const chart = parseFlowchart(text)+ const { addFlowchart } = await import('#core/io/formats/mermaid')+ const previousSelection = new Set(ctx.state.selectedIds)+ const parentId = resolvePasteTarget(ctx)+ const { ids: created } = await addFlowchart(ctx.graph, parentId, chart, {+ center: parentLocalPoint(parentId, cx, cy)+ })+ if (created.length === 0) return false+ ctx.setSelectedIds(new Set(created))+ pushCreatedNodesUndo(created, previousSelection, 'Paste Mermaid')+ ctx.requestRender()+ return true+ }+function placeImageFiles(files: File[], cx: number, cy: number) {return placeFiles(files.filter((file) => IMPORTABLE_RASTER_TYPES.has(file.type)),@@ -200,5 +221,5 @@ export function createClipboardAssetActions()}- return { storeImage, placeFiles, placeImageFiles, pasteSVG }+ return { storeImage, placeFiles, placeImageFiles, pasteSVG, pasteMermaid }}diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.tsindex 19239a783..06f0cd45e 100644--- a/packages/core/src/io/formats.ts+++ b/packages/core/src/io/formats.ts@@ -385,6 +385,31 @@ export const drawioFormat: IOFormatAdapter<'drawio'> = {}}+export const mermaidFormat: IOFormatAdapter<'mermaid'> = {+ id: 'mermaid',+ label: 'Mermaid Diagram',+ role: 'interchange-document',+ category: 'document',+ extensions: ['mmd', 'mermaid'],+ mimeTypes: ['text/vnd.mermaid'],+ support: {+ readDocument: true+ },+ laysOutOnRead: true,+ matchesFile(fileName, mimeType) {+ const ext = lowerExt(fileName)+ return ext === 'mmd' || ext === 'mermaid' || mimeType === 'text/vnd.mermaid'+ },+ async readDocument(input) {+ const { detectMermaidDiagram } = await import('@open-pencil/mermaid')+ const text = new TextDecoder().decode(input.data)+ if (!detectMermaidDiagram(text)) throw new Error('This file holds no Mermaid flowchart')+ // Mermaid stores a diagram's structure, which reading lays out with its text measured.+ const { mermaidToSceneGraph } = await import('./formats/mermaid')+ return { graph: await mermaidToSceneGraph(text), sourceFormat: 'mermaid' }+ }+}+/** Pages or layers as a draw.io file, loading the writer only when one is saved. */async function writeDrawIO(graph: SceneGraph, target: DrawIOExportTarget): Promise<ExportResult> {const { writeDrawIOFile } = await import('@open-pencil/drawio')@@ -588,6 +613,7 @@ export const BUILTIN_IO_FORMATS = [figFormat,penFormat,drawioFormat,+ mermaidFormat,pngFormat,jpgFormat,webpFormat,diff --git a/packages/core/src/io/formats/drawio/edges.ts b/packages/core/src/io/formats/drawio/edges.tsindex 7e2229b5d..586d43dbe 100644--- a/packages/core/src/io/formats/drawio/edges.ts+++ b/packages/core/src/io/formats/drawio/edges.ts@@ -1,6 +1,5 @@import type { DrawIOCell, DrawIOStyle } from '@open-pencil/drawio'import type {- ConnectorControlPoint,ConnectorEndpoint,ConnectorLabelPosition,ConnectorLineType,@@ -11,18 +10,16 @@ import type {} from '@open-pencil/scene-graph'import {boundEndpoint,- connectorRoute,connectorSublayers,createConnector,- curveControlPoints,- curveMidpoint,- dragCurve,freeEndpoint,layoutConnector} from '@open-pencil/scene-graph/connectors'import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'import type { Vector } from '@open-pencil/scene-graph/primitives'+import { bendConnectorThrough } from '#core/layout/diagram/routes'+import { readLabel } from './label'import { dashOf, labelFields, labelFormat, lineColor } from './paint'@@ -204,29 +201,6 @@ function endpointOf(return freeEndpoint(point?.x ?? 0, point?.y ?? 0)}-/**- * The control lines an elbow takes to run through an edge's bend points in turn: across to each- * point, then along to it, starting square to the side the connector leaves by.- */-function elbowThrough(points: Vector[], leavesAcross: boolean): ConnectorControlPoint[] {- const controls: ConnectorControlPoint[] = []- for (const point of points) {- const vertical: ConnectorControlPoint = { position: { ...point }, direction: 'VERTICAL' }- const horizontal: ConnectorControlPoint = { position: { ...point }, direction: 'HORIZONTAL' }- // A connector leaving sideways runs across to the point first.- const pair = leavesAcross ? [vertical, horizontal] : [horizontal, vertical]- for (const control of pair) {- const last = controls.at(-1)- if (last?.direction === control.direction) {- last.position = control.position- continue- }- controls.push(control)- }- }- return controls-}-/*** Joins a connector's ends to the layers its edge connects, routes it through the edge's bend* points, and gives it the edge's label where draw.io placed it. Labels beyond the first come@@ -261,37 +235,6 @@ export function bindEdge(graph.updateNode(connector.id, { connectorLabelPosition: labelPositionOf(at) })}layoutConnector(graph, connector)- routeThroughPoints(graph, connector, edge.geometry.points)+ bendConnectorThrough(graph, connector, edge.geometry.points)return extra}--/** Bends an elbow or a curve through an edge's points, in the connector's parent's axes. */-function routeThroughPoints(graph: SceneGraph, connector: SceneNode, points: Vector[]) {- if (points.length === 0) return- const node = graph.getNode(connector.id)- const route = node ? connectorRoute(graph, node) : null- if (!node || !route) return- const local = (point: Vector) => ({ x: point.x - node.x, y: point.y - node.y })- if (node.connectorLineType === 'CURVED') {- const curve = route.pieces.at(0)- if (!curve) return- // The curve bends so its middle passes the middle bend point.- const through = points[Math.floor(points.length / 2)]- const middle = curveMidpoint(curve)- const [first, second] = dragCurve(curveControlPoints(curve), {- x: through.x - middle.x,- y: through.y - middle.y- })- graph.updateNode(node.id, { connectorCurveHandles: [local(first), local(second)] })- } else {- const across = route.sides[0] === 'LEFT' || route.sides[0] === 'RIGHT'- graph.updateNode(node.id, {- connectorControlPoints: elbowThrough(points, across).map((control) => ({- ...control,- position: local(control.position)- }))- })- }- const updated = graph.getNode(node.id)- if (updated) layoutConnector(graph, updated)-}diff --git a/packages/core/src/io/formats/mermaid/index.ts b/packages/core/src/io/formats/mermaid/index.tsnew file mode 100644index 000000000..8311c324b--- /dev/null+++ b/packages/core/src/io/formats/mermaid/index.ts@@ -0,0 +1,20 @@+import { parseFlowchart } from '@open-pencil/mermaid'+import { SceneGraph } from '@open-pencil/scene-graph'++import { addFlowchart } from './layers'++export { addFlowchart, type FlowchartLayers } from './layers'++/**+ * A Mermaid flowchart as a FigJam board: one page named after the chart's title, with the chart's+ * nodes, subgraphs, and edges laid out on it.+ */+export async function mermaidToSceneGraph(text: string): Promise<SceneGraph> {+ const chart = parseFlowchart(text)+ const graph = new SceneGraph()+ const page = graph.getPages().at(0)+ if (!page) throw new Error('A new document has no page')+ if (chart.title) graph.updateNode(page.id, { name: chart.title })+ await addFlowchart(graph, page.id, chart)+ return graph+}diff --git a/packages/core/src/io/formats/mermaid/layers.ts b/packages/core/src/io/formats/mermaid/layers.tsnew file mode 100644index 000000000..d7fa5102c--- /dev/null+++ b/packages/core/src/io/formats/mermaid/layers.ts@@ -0,0 +1,299 @@+import type {+ FlowArrowhead,+ FlowEdge,+ FlowLabel,+ FlowNode,+ FlowSubgraph,+ Flowchart+} from '@open-pencil/mermaid'+import type { Fill, SceneGraph, SceneNode, Stroke, StrokeCap } from '@open-pencil/scene-graph'+import {+ connectorSublayers,+ createConnector,+ freeEndpoint+} from '@open-pencil/scene-graph/connectors'+import { BLACK } from '@open-pencil/scene-graph/constants'+import { createShapeWithText } from '@open-pencil/scene-graph/generated'+import type { Color } from '@open-pencil/scene-graph/primitives'++import { newLayerDefaults } from '#core/editor/shapes/defaults'+import { layoutAuthoredNodes } from '#core/layout'+import { layoutDiagram, type DiagramInput } from '#core/layout/diagram'+import { applyDiagramLayout, type DiagramPlacement } from '#core/layout/diagram/apply'+import { connectorLabelSize } from '#core/layout/diagram/routes'+import { shapeWithTextWidthFor } from '#core/layout/shape-with-text'+import { prepareGraphFonts } from '#core/text/prepare'++import { figJamShape } from './shapes'+import { declarationsFor, readStyle, type FlowStyle } from './styles'++/** Shape widths Mermaid's labels fit between, and how wide a label runs before it wraps. */+const MIN_SHAPE_WIDTH = 96+const MAX_SHAPE_WIDTH = 320+const LABEL_LINE_WIDTH = 200+/** The height a shape starts from; a label of more lines makes it taller. */+const SHAPE_HEIGHT = 56++/** How much wider Mermaid draws a thick edge, `==>`, than a normal one. */+const THICK = 1.5++/** Arrowheads as FigJam ends: Mermaid's filled triangle, dot, and cross. */+const CAPS: Record<FlowArrowhead, StrokeCap> = {+ none: 'NONE',+ arrow: 'ARROW_EQUILATERAL',+ circle: 'CIRCLE_FILLED',+ // FigJam has no cross end.+ cross: 'ARROW_LINES'+}++function solid(color: Color): Fill {+ return { type: 'SOLID', color: { ...color }, opacity: 1, visible: true }+}++/** Markdown's emphasis marks taken out, which a label shows as plain text for now. */+function labelText(label: FlowLabel): string {+ if (label.format === 'text') return label.text+ return label.text.replace(/(\*\*|__)(.+?)\1/g, '$2').replace(/([*_])(.+?)\1/g, '$2')+}++function styledFills(layer: Partial<SceneNode>, style: FlowStyle): Fill[] | undefined {+ if (style.fill === undefined) return layer.fills+ return style.fill === null ? [] : [solid(style.fill)]+}++/** A stroke with a Mermaid style's colour, width, and dashes over it. */+function styledStroke(base: Stroke, style: FlowStyle): Stroke {+ const stroke: Stroke = { ...base, color: { ...base.color }, align: 'CENTER' }+ if (style.stroke) stroke.color = { ...style.stroke }+ if (style.strokeWidth !== undefined) stroke.weight = style.strokeWidth+ if (style.dashPattern) stroke.dashPattern = style.dashPattern+ return stroke+}++/** A layer's paint with a Mermaid style over it: fill, outline colour, width, and dashes. */+function painted(layer: Partial<SceneNode>, style: FlowStyle): Partial<SceneNode> {+ const result: Partial<SceneNode> = { ...layer, fills: styledFills(layer, style) }+ if (style.stroke === null) {+ result.strokes = []+ return result+ }+ if (!style.stroke && style.strokeWidth === undefined && !style.dashPattern) return result+ const base = layer.strokes?.at(0) ?? {+ ...solid(style.stroke ?? BLACK),+ weight: 1,+ align: 'CENTER'+ }+ const stroke = styledStroke(base, style)+ result.strokes = [stroke]+ result.strokeWeight = stroke.weight+ if (style.dashPattern) result.dashPattern = style.dashPattern+ return result+}++/** Where each node and subgraph sits: the subgraph holding it, if any. */+function enclosingSubgraphs(chart: Flowchart): Map<string, string> {+ const enclosing = new Map<string, string>()+ for (const subgraph of chart.subgraphs) {+ for (const member of subgraph.members) enclosing.set(member, subgraph.id)+ }+ return enclosing+}++class FlowchartBuilder {+ /** The layer each node and subgraph became. */+ readonly layers = new Map<string, string>()+ readonly connectors = new Map<string, string>()+ private readonly enclosing: Map<string, string>++ constructor(+ private readonly graph: SceneGraph,+ private readonly parentId: string,+ private readonly chart: Flowchart+ ) {+ this.enclosing = enclosingSubgraphs(chart)+ }++ /** The layer a node or subgraph goes in: its subgraph's section, or the diagram's parent. */+ private parentOf(id: string): string {+ const subgraph = this.enclosing.get(id)+ return (subgraph && this.layers.get(subgraph)) ?? this.parentId+ }++ sections() {+ const byId = new Map(this.chart.subgraphs.map((subgraph) => [subgraph.id, subgraph]))+ const create = (subgraph: FlowSubgraph) => {+ if (this.layers.has(subgraph.id)) return+ const outer = this.enclosing.get(subgraph.id)+ const outerSubgraph = outer ? byId.get(outer) : undefined+ if (outerSubgraph) create(outerSubgraph)+ const style = readStyle(+ declarationsFor(this.chart.classDefs, subgraph.classes, subgraph.styles)+ )+ const section = this.graph.createNode('SECTION', this.parentOf(subgraph.id), {+ ...painted(newLayerDefaults('SECTION'), style),+ name: labelText(subgraph.title) || subgraph.id+ })+ this.layers.set(subgraph.id, section.id)+ }+ for (const subgraph of this.chart.subgraphs) create(subgraph)+ }++ shape(node: FlowNode) {+ const { graph } = this+ const kind = figJamShape(node.shape)+ const style = readStyle(declarationsFor(this.chart.classDefs, node.classes, node.styles))+ const defaults = newLayerDefaults('SHAPE_WITH_TEXT')+ // Mermaid's text block draws its label alone.+ const own = node.shape === 'text' ? { ...defaults, fills: [], strokes: [] } : defaults+ const text = labelText(node.label)+ const shape = createShapeWithText(+ graph,+ this.parentOf(node.id),+ {+ ...painted(own, style),+ shapeWithTextType: kind.type,+ flipY: kind.flipY ?? false,+ width: MIN_SHAPE_WIDTH,+ height: kind.round ? MIN_SHAPE_WIDTH : SHAPE_HEIGHT,+ shapeTruncates: false,+ name: text.split('\n')[0]?.trim() || node.id+ },+ style.color ? { text, fills: [solid(style.color)] } : { text }+ )+ this.layers.set(node.id, shape.id)+ }++ /** Widens a node's shape until its label runs no wider than a line, as Mermaid sizes it. */+ fitWidth(node: FlowNode) {+ const { graph } = this+ const layerId = this.layers.get(node.id)+ const shape = layerId ? graph.getNode(layerId) : undefined+ if (!shape) return+ const { round } = figJamShape(node.shape)+ const width = shapeWithTextWidthFor(+ graph,+ shape,+ { min: MIN_SHAPE_WIDTH, max: MAX_SHAPE_WIDTH, lineWidth: LABEL_LINE_WIDTH },+ (candidate) => (round ? candidate : SHAPE_HEIGHT)+ )+ const height = round ? width : SHAPE_HEIGHT+ graph.updateNode(shape.id, { width, height, shapeUserHeight: height })+ }++ /** A connector for each drawn edge, its ends free until the layout places them. */+ connector(edge: FlowEdge) {+ if (edge.stroke === 'invisible') return+ const { graph } = this+ const style = readStyle(edge.styles)+ const connector = createConnector(graph, this.parentId, {+ start: freeEndpoint(0, 0),+ end: freeEndpoint(0, 0),+ lineType: 'ELBOWED',+ startCap: CAPS[edge.startArrow],+ endCap: CAPS[edge.endArrow],+ text: edge.label ? labelText(edge.label) : ''+ })+ const parts = connectorSublayers(graph, connector)+ const stroke = parts?.line.strokes.at(0)+ if (parts && stroke) {+ const weight = edge.stroke === 'thick' ? stroke.weight * THICK : stroke.weight+ const line = styledStroke(+ {+ ...stroke,+ weight,+ dashPattern: edge.stroke === 'dotted' ? [weight * 2, weight * 2] : []+ },+ style+ )+ graph.updateNode(parts.line.id, {+ strokes: style.stroke === null ? [] : [line],+ strokeWeight: line.weight,+ dashPattern: line.dashPattern ?? []+ })+ if (style.color) graph.updateNode(parts.label.id, { fills: [solid(style.color)] })+ }+ this.connectors.set(edge.id, connector.id)+ }+}++/** What a flowchart became. */+export interface FlowchartLayers {+ /** The layers added to the parent, in order. */+ ids: string[]+ /** The layer each node and subgraph became, by its Mermaid id. */+ layers: Map<string, string>+ /** The connector each drawn edge became, by its Mermaid id. */+ connectors: Map<string, string>+}++/**+ * Adds a flowchart to `parentId` as FigJam layers, where `placement` puts it: each node a+ * shape with text sized to its label, each subgraph a section, and each edge an elbowed connector+ * joined to the layers it links, all laid out by ELK along the chart's direction, its text+ * measured in the fonts it is drawn in.+ */+export async function addFlowchart(+ graph: SceneGraph,+ parentId: string,+ chart: Flowchart,+ placement: DiagramPlacement = { topLeft: { x: 0, y: 0 } }+): Promise<FlowchartLayers> {+ const before = new Set(graph.getNode(parentId)?.childIds)+ const builder = new FlowchartBuilder(graph, parentId, chart)+ const addedSoFar = () => (graph.getNode(parentId)?.childIds ?? []).filter((id) => !before.has(id))+ // Known before the first wait, so a layer someone else adds meanwhile is never taken for ours.+ let created: string[] | null = null+ try {+ builder.sections()+ for (const node of chart.nodes) builder.shape(node)+ for (const edge of chart.edges) builder.connector(edge)+ const added = addedSoFar()+ created = added+ // Shapes grow to their labels, and connector labels take their size, before the layout reads+ // them, measured in the fonts they are drawn in.+ await prepareGraphFonts(graph, added)+ for (const node of chart.nodes) builder.fitWidth(node)+ layoutAuthoredNodes(graph, added)+ const enclosing = enclosingSubgraphs(chart)+ const size = (id: string) => {+ const layer = builder.layers.get(id)+ const node = layer ? graph.getNode(layer) : undefined+ return { width: node?.width ?? MIN_SHAPE_WIDTH, height: node?.height ?? SHAPE_HEIGHT }+ }+ const labelSize = (edgeId: string) => {+ const connectorId = builder.connectors.get(edgeId)+ return (connectorId && connectorLabelSize(graph, connectorId)) || undefined+ }+ const input: DiagramInput = {+ direction: chart.direction,+ nodes: chart.nodes.map((node) => ({+ id: node.id,+ ...size(node.id),+ group: enclosing.get(node.id)+ })),+ groups: chart.subgraphs.map((subgraph) => ({+ id: subgraph.id,+ group: enclosing.get(subgraph.id)+ })),+ edges: chart.edges.map((edge) => ({+ id: edge.id,+ from: edge.from,+ to: edge.to,+ label: labelSize(edge.id)+ }))+ }+ const layout = await layoutDiagram(input)+ applyDiagramLayout(+ graph,+ input,+ layout,+ { boxes: builder.layers, connectors: builder.connectors },+ placement+ )+ return { ids: added, layers: builder.layers, connectors: builder.connectors }+ } catch (error) {+ // A flowchart that fails to lay out leaves nothing half-built behind.+ for (const id of (created ?? addedSoFar()).toReversed()) graph.deleteNode(id)+ throw error+ }+}diff --git a/packages/core/src/io/formats/mermaid/shapes.ts b/packages/core/src/io/formats/mermaid/shapes.tsnew file mode 100644index 000000000..ac030a178--- /dev/null+++ b/packages/core/src/io/formats/mermaid/shapes.ts@@ -0,0 +1,81 @@+import type { FlowShape } from '@open-pencil/mermaid'+import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'++/** How a FigJam shape stands for a Mermaid one: its kind, and whether it is drawn upside down. */+export interface FigJamShape {+ type: ShapeWithTextType+ flipY?: boolean+ /** Whether Mermaid draws it as wide as it is tall, as circles. */+ round?: boolean+}++const SQUARE: FigJamShape = { type: 'SQUARE' }+const ROUNDED: FigJamShape = { type: 'ROUNDED_RECTANGLE' }+const CIRCLE: FigJamShape = { type: 'ELLIPSE', round: true }+const DATABASE: FigJamShape = { type: 'ENG_DATABASE' }+const DOCUMENT: FigJamShape = { type: 'DOCUMENT_SINGLE' }++/**+ * The FigJam shape each Mermaid shape becomes: the same figure where FigJam has one, else the+ * nearest, and a plain rectangle for figures FigJam has nothing like.+ */+const FIGJAM_SHAPES: Record<FlowShape, FigJamShape> = {+ rect: SQUARE,+ rounded: ROUNDED,+ stadium: ROUNDED,+ 'fr-rect': { type: 'PREDEFINED_PROCESS' },+ cyl: DATABASE,+ 'lin-cyl': DATABASE,+ datastore: DATABASE,+ 'h-cyl': { type: 'ENG_QUEUE' },+ folder: { type: 'ENG_FOLDER' },+ circle: CIRCLE,+ 'dbl-circ': CIRCLE,+ 'sm-circ': CIRCLE,+ 'fr-circ': CIRCLE,+ 'f-circ': CIRCLE,+ 'cross-circ': { type: 'SUMMING_JUNCTION', round: true },+ ellipse: { type: 'ELLIPSE' },+ diam: { type: 'DIAMOND' },+ hex: { type: 'HEXAGON' },+ 'lean-r': { type: 'PARALLELOGRAM_RIGHT' },+ 'lean-l': { type: 'PARALLELOGRAM_LEFT' },+ 'trap-b': { type: 'TRAPEZOID' },+ 'trap-t': { type: 'TRAPEZOID', flipY: true },+ tri: { type: 'TRIANGLE_UP' },+ 'flip-tri': { type: 'TRIANGLE_DOWN' },+ doc: DOCUMENT,+ 'lin-doc': DOCUMENT,+ 'tag-doc': DOCUMENT,+ docs: { type: 'DOCUMENT_MULTIPLE' },+ 'sl-rect': { type: 'MANUAL_INPUT' },+ 'win-pane': { type: 'INTERNAL_STORAGE' },+ 'notch-pent': { type: 'PENTAGON' },+ delay: ROUNDED,+ odd: SQUARE,+ flag: SQUARE,+ text: SQUARE,+ 'notch-rect': SQUARE,+ 'lin-rect': SQUARE,+ 'div-rect': SQUARE,+ 'st-rect': SQUARE,+ 'tag-rect': SQUARE,+ 'bow-rect': SQUARE,+ 'curv-trap': SQUARE,+ fork: SQUARE,+ hourglass: SQUARE,+ brace: SQUARE,+ 'brace-r': SQUARE,+ braces: SQUARE,+ bolt: SQUARE,+ bang: SQUARE,+ cloud: SQUARE,+ bucket: SQUARE,+ console: SQUARE,+ browser: SQUARE,+ person: SQUARE+}++export function figJamShape(shape: FlowShape): FigJamShape {+ return FIGJAM_SHAPES[shape]+}diff --git a/packages/core/src/io/formats/mermaid/styles.ts b/packages/core/src/io/formats/mermaid/styles.tsnew file mode 100644index 000000000..9863a3639--- /dev/null+++ b/packages/core/src/io/formats/mermaid/styles.ts@@ -0,0 +1,84 @@+import { tryParseColor } from '@open-pencil/scene-graph/color'+import { parseCSSNumber } from '@open-pencil/scene-graph/css'+import type { Color } from '@open-pencil/scene-graph/primitives'++/** What Mermaid's CSS declarations set that a layer can show; `null` colours are `none`. */+export interface FlowStyle {+ fill?: Color | null+ stroke?: Color | null+ strokeWidth?: number+ dashPattern?: number[]+ /** The label's colour. */+ color?: Color+}++function color(value: string): Color | null | undefined {+ if (value === 'none' || value === 'transparent') return null+ return tryParseColor(value) ?? undefined+}++/**+ * Mermaid's `fill:#f96`, `stroke-width:4px`, … declarations, later ones winning. Declarations no+ * layer property stands for, such as `font-family`, are left out.+ */+export function readStyle(declarations: Iterable<string>): FlowStyle {+ const style: FlowStyle = {}+ for (const declaration of declarations) {+ const colon = declaration.indexOf(':')+ if (colon === -1) continue+ const property = declaration.slice(0, colon).trim().toLowerCase()+ const value = declaration+ .slice(colon + 1)+ .replace(/!important/i, '')+ .trim()+ switch (property) {+ case 'fill':+ case 'background':+ case 'background-color': {+ const parsed = color(value)+ if (parsed !== undefined) style.fill = parsed+ break+ }+ case 'stroke': {+ const parsed = color(value)+ if (parsed !== undefined) style.stroke = parsed+ break+ }+ case 'color': {+ const parsed = color(value)+ if (parsed) style.color = parsed+ break+ }+ case 'stroke-width': {+ const width = parseCSSNumber(value)+ if (width !== null && width >= 0) style.strokeWidth = width+ break+ }+ case 'stroke-dasharray': {+ const dashes = value+ .split(/[\s,]+/)+ .map((part) => parseCSSNumber(part))+ .filter((part): part is number => part !== null && part >= 0)+ if (dashes.length > 0) style.dashPattern = dashes.some((dash) => dash > 0) ? dashes : []+ break+ }+ }+ }+ return style+}++/**+ * The declarations that style a node or subgraph: `classDef default`, then its classes in order,+ * then its own `style` statements.+ */+export function declarationsFor(+ classDefs: Map<string, string[]>,+ classes: string[],+ styles: string[]+): string[] {+ return [+ ...(classDefs.get('default') ?? []),+ ...classes.flatMap((name) => classDefs.get(name) ?? []),+ ...styles+ ]+}diff --git a/packages/core/src/layout/diagram/apply.ts b/packages/core/src/layout/diagram/apply.tsnew file mode 100644index 000000000..81bb8f40f--- /dev/null+++ b/packages/core/src/layout/diagram/apply.ts@@ -0,0 +1,88 @@+import type { SceneGraph } from '@open-pencil/scene-graph'+import { boundEndpoint } from '@open-pencil/scene-graph/connectors'+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'++import type { DiagramInput, DiagramLayout } from './index'+import { runConnectorAlong } from './routes'++/** The layers that draw a diagram, by the diagram's ids. */+export interface DiagramLayers {+ /** The layer drawing each node and group. */+ boxes: Map<string, string>+ /** The connector drawing each edge; an edge drawn by none only shapes the layout. */+ connectors: Map<string, string>+}++/** Where a diagram goes in its parent: by its top-left corner or by its centre. */+export type DiagramPlacement = { topLeft: Vector } | { center: Vector }++function bounds(boxes: Rect[]): Rect {+ const x = Math.min(...boxes.map((box) => box.x))+ const y = Math.min(...boxes.map((box) => box.y))+ return {+ x,+ y,+ width: Math.max(...boxes.map((box) => box.x + box.width)) - x,+ height: Math.max(...boxes.map((box) => box.y + box.height)) - y+ }+}++/**+ * Puts a diagram's layers where `layout` placed it, the drawing at `placement` in its parent:+ * each node's layer at its box and each group's at its box and size, in the axes of the group+ * holding it, if any. Each edge's connector is joined to the layers at its ends by the sides the+ * layout chose and runs along the route it gave.+ */+export function applyDiagramLayout(+ graph: SceneGraph,+ input: DiagramInput,+ layout: DiagramLayout,+ layers: DiagramLayers,+ placement: DiagramPlacement+): void {+ const boxes = new Map<string, Rect>([...layout.groups, ...layout.nodes])+ if (boxes.size === 0) return+ const drawing = bounds([...boxes.values()])+ const origin =+ 'center' in placement+ ? {+ x: placement.center.x - drawing.width / 2,+ y: placement.center.y - drawing.height / 2+ }+ : placement.topLeft+ const shift = { x: origin.x - drawing.x, y: origin.y - drawing.y }+ const groupOf = new Map(+ [...input.nodes, ...input.groups].map((member) => [member.id, member.group])+ )+ for (const [id, layerId] of layers.boxes) {+ const box = boxes.get(id)+ if (!box) continue+ const group = groupOf.get(id)+ const outer = group ? boxes.get(group) : undefined+ const position = outer+ ? { x: box.x - outer.x, y: box.y - outer.y }+ : { x: box.x + shift.x, y: box.y + shift.y }+ // A group's layer takes the size the layout gave it; a node's keeps its own.+ if (layout.groups.has(id)) {+ graph.updateNode(layerId, { ...position, width: box.width, height: box.height })+ } else {+ graph.updateNode(layerId, position)+ }+ }+ for (const edge of input.edges) {+ const connectorId = layers.connectors.get(edge.id)+ const start = layers.boxes.get(edge.from)+ const end = layers.boxes.get(edge.to)+ if (!connectorId || !start || !end) continue+ const route = layout.edges.get(edge.id)+ graph.updateNode(connectorId, {+ connectorStart: boundEndpoint(start, route?.startSide ?? 'AUTO'),+ connectorEnd: boundEndpoint(end, route?.endSide ?? 'AUTO')+ })+ runConnectorAlong(+ graph,+ connectorId,+ (route?.points ?? []).map((point) => ({ x: point.x + shift.x, y: point.y + shift.y }))+ )+ }+}diff --git a/packages/core/src/layout/diagram/elk.ts b/packages/core/src/layout/diagram/elk.tsnew file mode 100644index 000000000..0186c431c--- /dev/null+++ b/packages/core/src/layout/diagram/elk.ts@@ -0,0 +1,76 @@+import type { ELK, ElkNode } from 'elkjs/lib/elk-api'++import { IS_BROWSER } from '#core/constants'++/** A worker a runtime can stop counting as a reason to stay alive, as Bun's can. */+interface Unreffable {+ ref(): void+ unref(): void+}++function unreffable(worker: Worker): (Worker & Unreffable) | null {+ return 'ref' in worker && 'unref' in worker ? (worker as Worker & Unreffable) : null+}++interface Engine {+ elk: ELK+ /** ELK's worker, when it has one the runtime would otherwise wait for. */+ worker: () => Unreffable | null+}++let engine: Promise<Engine> | null = null+/** Layouts in flight. */+let running = 0++/**+ * Whether ELK's bundle would take this thread for a worker of its own, as it does wherever+ * `self` exists outside a page: in Bun, Deno, and Web Workers. It then answers messages instead+ * of laying out in place.+ */+function looksLikeWorker(): boolean {+ return !IS_BROWSER && 'self' in globalThis+}++async function load(): Promise<Engine> {+ if (!looksLikeWorker()) {+ const { default: BundledELK } = await import('elkjs/lib/elk.bundled.js')+ return { elk: new BundledELK(), worker: () => null }+ }+ // There, ELK's worker script runs in a real worker.+ const { default: WorkerELK } = await import('elkjs/lib/elk-api.js')+ const script = import.meta.resolve('elkjs/lib/elk-worker.min.js')+ let held: Unreffable | null = null+ const elk = new WorkerELK({+ workerFactory: () => {+ const worker = new Worker(script)+ held = unreffable(worker)+ // An idle worker must not keep a script or command from finishing.+ held?.unref()+ return worker+ }+ })+ return { elk, worker: () => held }+}++function elkEngine(): Promise<Engine> {+ engine ??= load().catch((error: unknown) => {+ engine = null+ throw error+ })+ return engine+}++/**+ * Lays `graph` out with the Eclipse Layout Kernel, loaded on first use and kept for later+ * layouts. Its worker, where it has one, keeps the process alive only while a layout runs.+ */+export async function layoutWithElk(graph: ElkNode): Promise<ElkNode> {+ const { elk, worker } = await elkEngine()+ const layout = elk.layout(graph)+ if (running++ === 0) worker()?.ref()+ try {+ return await layout+ } finally {+ if (--running === 0) worker()?.unref()+ }+}diff --git a/packages/core/src/layout/diagram/index.ts b/packages/core/src/layout/diagram/index.tsnew file mode 100644index 000000000..93e75c841--- /dev/null+++ b/packages/core/src/layout/diagram/index.ts@@ -0,0 +1,252 @@+import type { ElkExtendedEdge, ElkNode, ElkPort } from 'elkjs/lib/elk-api'++import type { ConnectorSide } from '@open-pencil/scene-graph/connectors'+import type { Rect, Size, Vector } from '@open-pencil/scene-graph/primitives'++import { layoutWithElk } from './elk'++/** The way a diagram flows: top to bottom, bottom to top, left to right, or right to left. */+export type DiagramDirection = 'TB' | 'BT' | 'LR' | 'RL'++/** A node or group, at the top or inside the group it names. */+export interface DiagramMember {+ id: string+ group?: string+}++export interface DiagramNode extends DiagramMember, Size {}++/** A box around nodes and other groups, sized to hold them. */+export type DiagramGroup = DiagramMember++/** An edge between two nodes or groups; its label, by size, gets room along it. */+export interface DiagramEdge {+ id: string+ from: string+ to: string+ label?: Size+}++export interface DiagramInput {+ direction: DiagramDirection+ nodes: DiagramNode[]+ groups: DiagramGroup[]+ edges: DiagramEdge[]+}++/** The way an edge runs: the sides it leaves and enters by, and its corners between them. */+export interface DiagramRoute {+ startSide: ConnectorSide+ endSide: ConnectorSide+ /** From its start, on the middle of `startSide`, to its end, on the middle of `endSide`. */+ points: Vector[]+}++/** Where everything went, in the diagram's own axes. */+export interface DiagramLayout {+ nodes: Map<string, Rect>+ groups: Map<string, Rect>+ edges: Map<string, DiagramRoute>+}++/** Room between nodes side by side, and between ranks of them along the flow. */+const NODE_SPACING = 40+const RANK_SPACING = 60+/** Room inside a group around what it holds, and above it for the group's title. */+const GROUP_PADDING = 24+const GROUP_TITLE = 48++const ELK_DIRECTION: Record<DiagramDirection, string> = {+ TB: 'DOWN',+ BT: 'UP',+ LR: 'RIGHT',+ RL: 'LEFT'+}++/** The side edges leave a box by, and the side they enter one by, along the flow. */+const FLOW_SIDES: Record<DiagramDirection, [ConnectorSide, ConnectorSide]> = {+ TB: ['BOTTOM', 'TOP'],+ BT: ['TOP', 'BOTTOM'],+ LR: ['RIGHT', 'LEFT'],+ RL: ['LEFT', 'RIGHT']+}++const ELK_SIDE: Record<ConnectorSide, string> = {+ TOP: 'NORTH',+ RIGHT: 'EAST',+ BOTTOM: 'SOUTH',+ LEFT: 'WEST'+}++function portId(boxId: string, side: ConnectorSide): string {+ return `${boxId}\u0000${side}`+}++/**+ * A port on the middle of each side a box's edges use, fixed there: connectors attach to side+ * midpoints, so ELK routes every edge to where its connector will meet the box.+ */+function ports(boxId: string, size: Size, sides: ConnectorSide[]): ElkPort[] {+ const at: Record<ConnectorSide, Vector> = {+ TOP: { x: size.width / 2, y: 0 },+ RIGHT: { x: size.width, y: size.height / 2 },+ BOTTOM: { x: size.width / 2, y: size.height },+ LEFT: { x: 0, y: size.height / 2 }+ }+ return sides.map((side) => ({+ id: portId(boxId, side),+ ...at[side],+ width: 0,+ height: 0,+ layoutOptions: { 'elk.port.side': ELK_SIDE[side] }+ }))+}++/** Each box's place in the input: a node's own, a group's that of its first member. */+function writtenOrder(input: DiagramInput): Map<string, number> {+ const order = new Map<string, number>()+ const groupOf = new Map(input.groups.map((group) => [group.id, group.group]))+ for (const [index, node] of input.nodes.entries()) {+ order.set(node.id, index)+ for (let group = node.group; group !== undefined; group = groupOf.get(group)) {+ if (!order.has(group)) order.set(group, index)+ }+ }+ return order+}++function elkGraph(input: DiagramInput): ElkNode {+ const [outSide, inSide] = FLOW_SIDES[input.direction]+ const boxes = new Map<string, ElkNode>()+ for (const group of input.groups) {+ boxes.set(group.id, {+ id: group.id,+ children: [],+ layoutOptions: {+ 'elk.padding': `[top=${GROUP_TITLE},left=${GROUP_PADDING},bottom=${GROUP_PADDING},right=${GROUP_PADDING}]`,+ 'elk.portConstraints': 'FIXED_SIDE'+ },+ ports: [+ { id: portId(group.id, outSide), layoutOptions: { 'elk.port.side': ELK_SIDE[outSide] } },+ { id: portId(group.id, inSide), layoutOptions: { 'elk.port.side': ELK_SIDE[inSide] } }+ ]+ })+ }+ for (const node of input.nodes) {+ boxes.set(node.id, {+ id: node.id,+ width: node.width,+ height: node.height,+ layoutOptions: { 'elk.portConstraints': 'FIXED_POS' },+ ports: ports(node.id, node, [outSide, inSide])+ })+ }+ const root: ElkNode = {+ id: '\u0000root',+ layoutOptions: {+ 'elk.algorithm': 'layered',+ 'elk.direction': ELK_DIRECTION[input.direction],+ 'elk.hierarchyHandling': 'INCLUDE_CHILDREN',+ 'elk.edgeRouting': 'ORTHOGONAL',+ 'elk.spacing.nodeNode': String(NODE_SPACING),+ 'elk.layered.spacing.nodeNodeBetweenLayers': String(RANK_SPACING),+ 'elk.spacing.edgeNode': '20',+ 'elk.spacing.edgeEdge': '12',+ 'elk.layered.spacing.edgeNodeBetweenLayers': '20',+ 'elk.spacing.componentComponent': String(RANK_SPACING),+ // Flowcharts read from their first node: break cycles along the order they were written+ // in, rather than where ELK's greedy pass would, which can put the start mid-drawing.+ 'elk.layered.cycleBreaking.strategy': 'DEPTH_FIRST',+ 'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',+ 'elk.edgeLabels.placement': 'CENTER',+ 'elk.json.shapeCoords': 'ROOT',+ 'elk.json.edgeCoords': 'ROOT'+ },+ children: [],+ edges: []+ }+ const parentOf = (group: string | undefined) => (group ? boxes.get(group) : undefined) ?? root+ // ELK keeps the order it is given, so boxes go in the order they were written: a node where it+ // first appears, a group where its first member does.+ const order = writtenOrder(input)+ const members = [...input.groups, ...input.nodes].sort(+ (a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0)+ )+ for (const member of members) {+ const box = boxes.get(member.id)+ if (box) parentOf(member.group).children?.push(box)+ }+ root.edges = input.edges+ .filter((edge) => boxes.has(edge.from) && boxes.has(edge.to))+ .map((edge): ElkExtendedEdge => ({+ id: edge.id,+ sources: [portId(edge.from, outSide)],+ targets: [portId(edge.to, inSide)],+ // ELK skips a label without text; only its size matters here.+ labels: edge.label ? [{ text: edge.id, ...edge.label }] : []+ }))+ return root+}++function sideOf(point: Vector, box: Rect): ConnectorSide {+ const distances: [ConnectorSide, number][] = [+ ['TOP', Math.abs(point.y - box.y)],+ ['RIGHT', Math.abs(point.x - (box.x + box.width))],+ ['BOTTOM', Math.abs(point.y - (box.y + box.height))],+ ['LEFT', Math.abs(point.x - box.x)]+ ]+ return distances.reduce((best, entry) => (entry[1] < best[1] ? entry : best))[0]+}++function collect(result: ElkNode, input: DiagramInput): DiagramLayout {+ const groupIds = new Set(input.groups.map((group) => group.id))+ const layout: DiagramLayout = { nodes: new Map(), groups: new Map(), edges: new Map() }+ const boxes = new Map<string, Rect>()+ const walk = (node: ElkNode) => {+ for (const child of node.children ?? []) {+ const rect = {+ x: child.x ?? 0,+ y: child.y ?? 0,+ width: child.width ?? 0,+ height: child.height ?? 0+ }+ boxes.set(child.id, rect)+ ;(groupIds.has(child.id) ? layout.groups : layout.nodes).set(child.id, rect)+ walk(child)+ }+ }+ walk(result)+ const edgesOf = (node: ElkNode): ElkExtendedEdge[] => [+ ...(node.edges ?? []),+ ...(node.children ?? []).flatMap(edgesOf)+ ]+ const ends = new Map(input.edges.map((edge) => [edge.id, edge]))+ for (const edge of edgesOf(result)) {+ const input = ends.get(edge.id)+ const from = input && boxes.get(input.from)+ const to = input && boxes.get(input.to)+ const points = (edge.sections ?? []).flatMap((section) => [+ section.startPoint,+ ...(section.bendPoints ?? []),+ section.endPoint+ ])+ const first = points.at(0)+ const last = points.at(-1)+ if (!from || !to || !first || !last) continue+ layout.edges.set(edge.id, {+ startSide: sideOf(first, from),+ endSide: sideOf(last, to),+ points: points.map(({ x, y }) => ({ x, y }))+ })+ }+ return layout+}++/**+ * Lays a diagram out with ELK's layered algorithm: nodes in ranks along the flow, groups around+ * their members, and every edge routed at right angles from the middle of the side it leaves by+ * to the middle of the side it enters by.+ */+export async function layoutDiagram(input: DiagramInput): Promise<DiagramLayout> {+ return collect(await layoutWithElk(elkGraph(input)), input)+}diff --git a/packages/core/src/layout/diagram/routes.ts b/packages/core/src/layout/diagram/routes.tsnew file mode 100644index 000000000..6533a6f3f--- /dev/null+++ b/packages/core/src/layout/diagram/routes.ts@@ -0,0 +1,117 @@+import type { ConnectorControlPoint, SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import {+ connectorRoute,+ connectorSublayers,+ CONNECTOR_LABEL_PADDING,+ curveControlPoints,+ curveMidpoint,+ dragCurve,+ elbowControlPoints,+ layoutConnector,+ type ConnectorPiece+} from '@open-pencil/scene-graph/connectors'+import type { Size, Vector } from '@open-pencil/scene-graph/primitives'++/**+ * The control lines an elbow takes to run through bend points in turn: across to each point,+ * then along to it, starting square to the side the connector leaves by.+ */+function elbowThrough(points: Vector[], leavesAcross: boolean): ConnectorControlPoint[] {+ const controls: ConnectorControlPoint[] = []+ for (const point of points) {+ const vertical: ConnectorControlPoint = { position: { ...point }, direction: 'VERTICAL' }+ const horizontal: ConnectorControlPoint = { position: { ...point }, direction: 'HORIZONTAL' }+ // A connector leaving sideways runs across to the point first.+ const pair = leavesAcross ? [vertical, horizontal] : [horizontal, vertical]+ for (const control of pair) {+ const last = controls.at(-1)+ if (last?.direction === control.direction) {+ last.position = control.position+ continue+ }+ controls.push(control)+ }+ }+ return controls+}++/** Points in the connector's parent's axes as points in its own. */+function local(node: SceneNode, point: Vector): Vector {+ return { x: point.x - node.x, y: point.y - node.y }+}++function relayout(graph: SceneGraph, connectorId: string): void {+ const node = graph.getNode(connectorId)+ if (node) layoutConnector(graph, node)+}++/**+ * Bends an elbow or a curve through bend points, in the connector's parent's axes, as a drawing+ * tool's edge passes through the points it stores: an elbow runs through each in turn, a curve's+ * middle passes the middle one.+ */+export function bendConnectorThrough(+ graph: SceneGraph,+ connector: SceneNode,+ points: Vector[]+): void {+ if (points.length === 0) return+ const node = graph.getNode(connector.id)+ const route = node ? connectorRoute(graph, node) : null+ if (!node || !route) return+ if (node.connectorLineType === 'CURVED') {+ const curve = route.pieces.at(0)+ if (!curve) return+ const through = points[Math.floor(points.length / 2)]+ const middle = curveMidpoint(curve)+ const [first, second] = dragCurve(curveControlPoints(curve), {+ x: through.x - middle.x,+ y: through.y - middle.y+ })+ graph.updateNode(node.id, { connectorCurveHandles: [local(node, first), local(node, second)] })+ } else {+ const across = route.sides[0] === 'LEFT' || route.sides[0] === 'RIGHT'+ graph.updateNode(node.id, {+ connectorControlPoints: elbowThrough(points, across).map((control) => ({+ ...control,+ position: local(node, control.position)+ }))+ })+ }+ relayout(graph, node.id)+}++/**+ * Runs an elbow along a right-angled route, in the connector's parent's axes, from its start to+ * its end: each segment between the first and the last becomes a dragged segment, as FigJam+ * records an elbow that was edited into that shape.+ */+export function runConnectorAlong(graph: SceneGraph, connectorId: string, route: Vector[]): void {+ relayout(graph, connectorId)+ const node = graph.getNode(connectorId)+ if (!node) return+ const pieces: ConnectorPiece[] = route.slice(1).map((to, index) => ({+ from: route[index] ?? to,+ to,+ handleFrom: { x: 0, y: 0 },+ handleTo: { x: 0, y: 0 }+ }))+ graph.updateNode(connectorId, {+ connectorControlPoints: elbowControlPoints(pieces).map((control) => ({+ ...control,+ position: local(node, control.position)+ }))+ })+ relayout(graph, connectorId)+}++/** The room a connector's label takes along its line, or null for a connector without one. */+export function connectorLabelSize(graph: SceneGraph, connectorId: string): Size | null {+ const connector = graph.getNode(connectorId)+ const label = connector ? connectorSublayers(graph, connector)?.label : undefined+ if (!label?.text) return null+ return {+ width: label.width + 2 * CONNECTOR_LABEL_PADDING,+ height: label.height + 2 * CONNECTOR_LABEL_PADDING+ }+}diff --git a/packages/core/src/layout/shape-with-text.ts b/packages/core/src/layout/shape-with-text.tsindex 0436b9d84..8218895db 100644--- a/packages/core/src/layout/shape-with-text.ts+++ b/packages/core/src/layout/shape-with-text.ts@@ -31,6 +31,38 @@ export function shapeWithTextFit(graph: SceneGraph, shape: SceneNode): Partial<Sreturn { height, ...shapeWithTextFrameFields(shape.shapeWithTextType, shape.width, height) }}+/** Wider than any label lays out, for measuring one on a single line. */+const UNWRAPPED = 100_000++/**+ * The narrowest whole width, from `min` to `max`, whose label box holds the shape's label in lines+ * no wider than `lineWidth`, with the height `heightFor` gives each width. The label wraps past+ * `lineWidth`, and the shape's fit then makes it taller.+ */+export function shapeWithTextWidthFor(+ graph: SceneGraph,+ shape: SceneNode,+ { min, max, lineWidth }: { min: number; max: number; lineWidth: number },+ heightFor: (width: number) => number = () => shape.height+): number {+ const label = shapeWithTextLabel(graph, shape)+ if (!label?.text) return min+ const natural = measureTextForLayout(wholeText(label, UNWRAPPED), UNWRAPPED).width+ const needed = Math.min(Math.ceil(natural), lineWidth)+ const holds = (width: number) =>+ shapeWithTextLabelBox(shape.shapeWithTextType, width, heightFor(width)).width >= needed+ if (holds(min)) return min+ if (!holds(max)) return max+ let low = min+ let high = max+ while (high - low > 1) {+ const middle = Math.floor((low + high) / 2)+ if (holds(middle)) high = middle+ else low = middle+ }+ return high+}+/** A label's whole text wrapped at `width`, not cut short by a truncation it already has. */function wholeText(label: SceneNode, width: number): SceneNode {return {diff --git a/packages/core/src/tools/create.ts b/packages/core/src/tools/create.tsindex 8f73fb06d..6362e6acb 100644--- a/packages/core/src/tools/create.ts+++ b/packages/core/src/tools/create.ts@@ -8,6 +8,7 @@ export {} from './create/components'export { fetchIconsTool, insertIcon, searchIconsTool } from './create/icons'export { render } from './create/render'+export { importMermaid } from './create/mermaid'export { importSVG } from './create/svg'export { createVector } from './create/vector'export { createConnectorTool } from './create/connector'diff --git a/packages/core/src/tools/create/mermaid.ts b/packages/core/src/tools/create/mermaid.tsnew file mode 100644index 000000000..5da4fc935--- /dev/null+++ b/packages/core/src/tools/create/mermaid.ts@@ -0,0 +1,62 @@+import * as v from 'valibot'++import { detectMermaidDiagram, parseFlowchart } from '@open-pencil/mermaid'+import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'++import { addFlowchart } from '#core/io/formats/mermaid'+import { toolNumber, defineTool } from '#core/tools/schema'++/** Room left between a parent's content and a diagram placed beside it. */+const BESIDE_GAP = 100++export const importMermaid = defineTool({+ name: 'import_mermaid',++ description:+ 'Import a Mermaid flowchart (`flowchart` or `graph`) as editable FigJam layers, laid out automatically so nothing overlaps: each node a shape with text in its Mermaid shape, each subgraph a section, and each edge an elbowed connector joined to the layers it links, with its arrowheads, dotted or thick line, and label. classDef, class, and style fills, strokes, and text colours carry over. Without x and y the diagram goes to the right of what the parent already holds. Returns the layer id of every node and subgraph and the connector id of every edge, by Mermaid id.',+ execution: { kind: 'async', mutation: 'document' },+ input: v.strictObject({+ mermaid: v.pipe(+ v.string(),+ v.description('Mermaid flowchart source (e.g. "flowchart LR\\n A[Start] --> B{Ready?}")')+ ),+ parent_id: v.optional(v.pipe(v.string(), v.description('Parent node ID (default: the page)'))),+ x: v.optional(toolNumber(v.pipe(v.number(), v.description('X of the diagram’s left edge')))),+ y: v.optional(toolNumber(v.pipe(v.number(), v.description('Y of the diagram’s top edge'))))+ }),+ execute: async (figma, args) => {+ if (detectMermaidDiagram(args.mermaid) !== 'flowchart') {+ return {+ error: 'Only Mermaid flowcharts, starting with `flowchart` or `graph`, are supported'+ }+ }+ let chart+ try {+ chart = parseFlowchart(args.mermaid)+ } catch (error) {+ return { error: error instanceof Error ? error.message : String(error) }+ }+ const { graph } = figma+ const parentId = args.parent_id ?? figma.currentPage.id+ if (!graph.getNode(parentId)) return { error: `Parent ${parentId} not found` }+ const content = graph.getNode(parentId)?.childIds ?? []+ const bounds =+ content.length > 0+ ? getAxisAlignedBoundsInParent(+ content.flatMap((id) => graph.getNode(id) ?? []),+ parentId,+ graph+ )+ : null+ const topLeft = {+ x: args.x ?? (bounds ? bounds.x + bounds.width + BESIDE_GAP : 0),+ y: args.y ?? bounds?.y ?? 0+ }+ const result = await addFlowchart(graph, parentId, chart, { topLeft })+ return {+ ids: result.ids,+ nodes: Object.fromEntries(result.layers),+ connectors: Object.fromEntries(result.connectors)+ }+ }+})diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex a5c64b27a..d7f9d3adf 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -44,7 +44,7 @@ export {parseOverlapSeverity} from './analyze/overlaps/params'export { setPexelsAPIKey, setUnsplashAccessKey } from './stock-photo'-export { importSVG } from './create'+export { importMermaid, importSVG } from './create'export {getStockPhotoProviders,registerStockPhotoProvider,diff --git a/packages/core/src/tools/registry/extended.ts b/packages/core/src/tools/registry/extended.tsindex 5b55660a1..0dec1e1e9 100644--- a/packages/core/src/tools/registry/extended.ts+++ b/packages/core/src/tools/registry/extended.ts@@ -24,6 +24,7 @@ import {createSlot,fetchIconsTool,getBehaviour,+ importMermaid,importSVG,insertIcon,searchIconsTool,@@ -150,6 +151,7 @@ export const EXTENDED_TOOLS: ToolDef[] = [createSlice,createConnectorTool,importSVG,+ importMermaid,// Modify (advanced)setEffects,setOpacity,diff --git a/packages/core/tests/editor/clipboard/mermaid-paste.test.ts b/packages/core/tests/editor/clipboard/mermaid-paste.test.tsnew file mode 100644index 000000000..aee4fef4f--- /dev/null+++ b/packages/core/tests/editor/clipboard/mermaid-paste.test.ts@@ -0,0 +1,36 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core'+import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'++describe('pasting Mermaid text', () => {+ test('lays the flowchart out centred on the point, selected, as one undo entry', async () => {+ const editor = createEditor()+ const pageId = editor.state.currentPageId++ expect(await editor.pasteMermaid('flowchart TD\n A[Start] --> B[End]', 500, 300)).toBe(true)++ const layers = editor.graph.getChildren(pageId)+ expect(layers.map((node) => node.type).sort()).toEqual([+ 'CONNECTOR',+ 'SHAPE_WITH_TEXT',+ 'SHAPE_WITH_TEXT'+ ])+ const shapes = layers.filter((node) => node.type === 'SHAPE_WITH_TEXT')+ const bounds = getAxisAlignedBoundsInParent(shapes, pageId, editor.graph)+ expect(bounds.x + bounds.width / 2).toBeCloseTo(500, 0)+ expect(bounds.y + bounds.height / 2).toBeCloseTo(300, 0)+ expect(editor.state.selectedIds.size).toBe(3)+ expect(editor.undo.undoLabel).toBe('Paste Mermaid')++ editor.undoAction()+ expect(editor.graph.getChildren(pageId)).toHaveLength(0)+ })++ test('leaves text that is not a Mermaid flowchart to other paste handlers', async () => {+ const editor = createEditor()+ expect(await editor.pasteMermaid('graphical interfaces', 0, 0)).toBe(false)+ expect(await editor.pasteMermaid('sequenceDiagram\n A->>B: hi', 0, 0)).toBe(false)+ expect(editor.graph.getChildren(editor.state.currentPageId)).toHaveLength(0)+ })+})diff --git a/packages/core/tests/io/formats/mermaid/import.test.ts b/packages/core/tests/io/formats/mermaid/import.test.tsnew file mode 100644index 000000000..e4a46149a--- /dev/null+++ b/packages/core/tests/io/formats/mermaid/import.test.ts@@ -0,0 +1,185 @@+import { describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { colorToHex } from '@open-pencil/scene-graph/color'+import { connectorSublayers } from '@open-pencil/scene-graph/connectors'+import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'+import { shapeWithTextLabel } from '@open-pencil/scene-graph/generated'+import type { Rect } from '@open-pencil/scene-graph/primitives'++import { BUILTIN_IO_FORMATS, IORegistry } from '#core/io'++const io = new IORegistry(BUILTIN_IO_FORMATS)++async function read(source: string, name = 'flow.mmd') {+ const { graph } = await io.readDocument({ name, data: new TextEncoder().encode(source) })+ return graph+}++function page(graph: SceneGraph): SceneNode {+ return expectDefined(graph.getPages()[0])+}++function shapes(graph: SceneGraph): SceneNode[] {+ return [...graph.getAllNodes()].filter((node) => node.type === 'SHAPE_WITH_TEXT')+}++function named(graph: SceneGraph, name: string): SceneNode {+ return expectDefined(+ [...graph.getAllNodes()].find((node) => node.name === name),+ name+ )+}++function labelOf(graph: SceneGraph, node: SceneNode): string {+ return shapeWithTextLabel(graph, node)?.text ?? connectorSublayers(graph, node)?.label.text ?? ''+}++function connectors(graph: SceneGraph): SceneNode[] {+ return [...graph.getAllNodes()].filter((node) => node.type === 'CONNECTOR')+}++/** A layer's box on the page. */+function box(graph: SceneGraph, node: SceneNode): Rect {+ return getAxisAlignedBoundsInParent([node], page(graph).id, graph)+}++function overlap(a: Rect, b: Rect): boolean {+ return a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height+}++function contains(outer: Rect, inner: Rect): boolean {+ return (+ inner.x >= outer.x &&+ inner.y >= outer.y &&+ inner.x + inner.width <= outer.x + outer.width &&+ inner.y + inner.height <= outer.y + outer.height+ )+}++const CHECKOUT = `---+title: Checkout+---+flowchart TD+ A[Start] --> B{Cart empty?}+ B -- Yes --> C(Suggest items)+ B -->|No| D[[Collect payment]]+ subgraph F [Fulfilment]+ D --> E[(Orders)]+ subgraph W [Warehouse]+ E --> G((Shipped))+ end+ end+ C -.-> A+ C ==> G+ G ~~~ A`++describe('opening Mermaid files', () => {+ test('takes .mmd and .mermaid files and refuses diagrams other than flowcharts', async () => {+ const format = expectDefined(io.getFormat('mermaid'))+ expect(format.matchesFile?.('flow.mmd')).toBe(true)+ expect(format.matchesFile?.('flow.mermaid')).toBe(true)+ expect(format.matchesFile?.('flow.md')).toBe(false)+ await expect(read('sequenceDiagram\nA->>B: hi')).rejects.toThrow('no Mermaid flowchart')+ })++ test('makes a page named after the title, with a shape per node and a section per subgraph', async () => {+ const graph = await read(CHECKOUT)+ expect(page(graph).name).toBe('Checkout')+ const kinds = Object.fromEntries(+ shapes(graph).map((shape) => [labelOf(graph, shape), shape.shapeWithTextType])+ )+ expect(kinds).toEqual({+ Start: 'SQUARE',+ 'Cart empty?': 'DIAMOND',+ 'Suggest items': 'ROUNDED_RECTANGLE',+ 'Collect payment': 'PREDEFINED_PROCESS',+ Orders: 'ENG_DATABASE',+ Shipped: 'ELLIPSE'+ })+ const fulfilment = named(graph, 'Fulfilment')+ const warehouse = named(graph, 'Warehouse')+ expect(fulfilment.type).toBe('SECTION')+ expect(warehouse.parentId).toBe(fulfilment.id)+ // A node belongs to the subgraph that closes first, as in Mermaid.+ expect(named(graph, 'Collect payment').parentId).toBe(fulfilment.id)+ expect(named(graph, 'Orders').parentId).toBe(warehouse.id)+ expect(named(graph, 'Shipped').parentId).toBe(warehouse.id)+ expect(named(graph, 'Start').parentId).toBe(page(graph).id)+ })++ test('lays the chart out along its direction without overlaps, sections around their members', async () => {+ const graph = await read(CHECKOUT)+ const boxes = shapes(graph).map((shape) => box(graph, shape))+ for (const [i, a] of boxes.entries()) {+ for (const b of boxes.slice(i + 1)) expect(overlap(a, b)).toBe(false)+ }+ const start = box(graph, named(graph, 'Start'))+ const decision = box(graph, named(graph, 'Cart empty?'))+ expect(start.y + start.height).toBeLessThan(decision.y)+ expect(+ contains(box(graph, named(graph, 'Fulfilment')), box(graph, named(graph, 'Collect payment')))+ ).toBe(true)+ expect(+ contains(box(graph, named(graph, 'Warehouse')), box(graph, named(graph, 'Shipped')))+ ).toBe(true)++ const across = await read('flowchart LR\n A --> B')+ const [a, b] = ['A', 'B'].map((name) => box(across, named(across, name)))+ expect(expectDefined(a).x + expectDefined(a).width).toBeLessThan(expectDefined(b).x)+ })++ test('joins a connector per drawn edge to its layers by the sides the flow takes', async () => {+ const graph = await read(CHECKOUT)+ const lines = connectors(graph)+ // `~~~` lays the chart out but draws nothing.+ expect(lines).toHaveLength(7)+ const joined = (from: string, to: string) =>+ expectDefined(+ lines.find(+ (line) =>+ line.connectorStart?.nodeId === named(graph, from).id &&+ line.connectorEnd?.nodeId === named(graph, to).id+ ),+ `${from} → ${to}`+ )+ const first = joined('Start', 'Cart empty?')+ expect([first.connectorStart?.magnet, first.connectorEnd?.magnet]).toEqual(['BOTTOM', 'TOP'])+ expect(first.connectorLineType).toBe('ELBOWED')+ expect([first.connectorStartCap, first.connectorEndCap]).toEqual(['NONE', 'ARROW_EQUILATERAL'])+ expect(labelOf(graph, joined('Cart empty?', 'Suggest items'))).toBe('Yes')+ expect(labelOf(graph, joined('Cart empty?', 'Collect payment'))).toBe('No')++ const lineOf = (connector: SceneNode) =>+ expectDefined(connectorSublayers(graph, connector)).line+ const plain = lineOf(first)+ const dotted = lineOf(joined('Suggest items', 'Start'))+ const thick = lineOf(joined('Suggest items', 'Shipped'))+ expect(plain.dashPattern).toEqual([])+ expect(dotted.dashPattern.length).toBeGreaterThan(0)+ expect(thick.strokeWeight).toBeGreaterThan(plain.strokeWeight)+ })++ test('carries classDef, class, style, and linkStyle colours over', async () => {+ const graph = await read(`flowchart LR+ A:::hot --> B --> C+ classDef hot fill:#ffd6a5,stroke:#e85d04,color:#7a2e00+ classDef default fill:#eeeeee+ style B stroke:#2a9d8f,stroke-width:2px+ linkStyle 1 stroke:#ff0000`)+ const a = named(graph, 'A')+ const b = named(graph, 'B')+ expect(colorToHex(expectDefined(a.fills[0]).color)).toBe('#FFD6A5')+ expect(colorToHex(expectDefined(a.strokes[0]).color)).toBe('#E85D04')+ expect(colorToHex(expectDefined(shapeWithTextLabel(graph, a)?.fills[0]).color)).toBe('#7A2E00')+ expect(colorToHex(expectDefined(b.fills[0]).color)).toBe('#EEEEEE')+ expect(b.strokes[0]).toMatchObject({ weight: 2 })+ const second = expectDefined(+ connectors(graph).find((line) => line.connectorStart?.nodeId === b.id)+ )+ const line = expectDefined(connectorSublayers(graph, second)).line+ expect(colorToHex(expectDefined(line.strokes[0]).color)).toBe('#FF0000')+ })+})diff --git a/packages/core/tests/layout/diagram/apply.test.ts b/packages/core/tests/layout/diagram/apply.test.tsnew file mode 100644index 000000000..6d31920c2--- /dev/null+++ b/packages/core/tests/layout/diagram/apply.test.ts@@ -0,0 +1,114 @@+import { describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { SceneGraph } from '@open-pencil/scene-graph'+import { connectorRoute, createConnector, freeEndpoint } from '@open-pencil/scene-graph/connectors'++import { layoutDiagram, type DiagramInput } from '#core/layout/diagram'+import { applyDiagramLayout } from '#core/layout/diagram/apply'++describe('applyDiagramLayout', () => {+ test('arranges existing layers and joins their connector by the sides the layout chose', async () => {+ const graph = new SceneGraph()+ const pageId = expectDefined(graph.getPages()[0]).id+ const section = graph.createNode('SECTION', pageId, { x: 500, y: 500 })+ const first = graph.createNode('RECTANGLE', pageId, { x: 300, y: 300, width: 100, height: 40 })+ const second = graph.createNode('RECTANGLE', section.id, { width: 100, height: 40 })+ const connector = createConnector(graph, pageId, {+ start: freeEndpoint(0, 0),+ end: freeEndpoint(0, 0)+ })+ const input: DiagramInput = {+ direction: 'LR',+ nodes: [+ { id: 'a', width: 100, height: 40 },+ { id: 'b', width: 100, height: 40, group: 'g' }+ ],+ groups: [{ id: 'g' }],+ edges: [{ id: 'ab', from: 'a', to: 'b' }]+ }+ const layout = await layoutDiagram(input)++ applyDiagramLayout(+ graph,+ input,+ layout,+ {+ boxes: new Map([+ ['a', first.id],+ ['b', second.id],+ ['g', section.id]+ ]),+ connectors: new Map([['ab', connector.id]])+ },+ { topLeft: { x: 0, y: 0 } }+ )++ const placedFirst = expectDefined(graph.getNode(first.id))+ const placedSection = expectDefined(graph.getNode(section.id))+ const placedSecond = expectDefined(graph.getNode(second.id))+ // The drawing starts at the top-left corner it was given.+ expect(Math.min(placedFirst.x, placedSection.x)).toBe(0)+ expect(Math.min(placedFirst.y, placedSection.y)).toBe(0)+ // The group's layer takes the layout's size and holds its member in its own axes.+ expect(placedSection.width).toBe(expectDefined(layout.groups.get('g')).width)+ expect(placedSecond.x).toBeGreaterThan(0)+ expect(placedSecond.x + placedSecond.width).toBeLessThan(placedSection.width)+ expect(placedFirst.x + placedFirst.width).toBeLessThan(placedSection.x)+ const joined = expectDefined(graph.getNode(connector.id))+ expect(joined.connectorStart).toMatchObject({ nodeId: first.id, magnet: 'RIGHT' })+ expect(joined.connectorEnd).toMatchObject({ nodeId: second.id, magnet: 'LEFT' })+ })+})++describe('applyDiagramLayout routes', () => {+ test('runs each connector through the corners of the route the layout gave it', async () => {+ const graph = new SceneGraph()+ const pageId = expectDefined(graph.getPages()[0]).id+ const box = () => graph.createNode('RECTANGLE', pageId, { width: 100, height: 40 }).id+ const boxes = new Map([+ ['a', box()],+ ['b', box()],+ ['c', box()]+ ])+ const connector = () =>+ createConnector(graph, pageId, { start: freeEndpoint(0, 0), end: freeEndpoint(0, 0) }).id+ const connectors = new Map([+ ['ab', connector()],+ ['ac', connector()]+ ])+ const input: DiagramInput = {+ direction: 'TB',+ nodes: ['a', 'b', 'c'].map((id) => ({ id, width: 100, height: 40 })),+ groups: [],+ edges: [+ { id: 'ab', from: 'a', to: 'b' },+ { id: 'ac', from: 'a', to: 'c' }+ ]+ }+ const layout = await layoutDiagram(input)+ const origin = { x: 1000, y: 2000 }++ applyDiagramLayout(graph, input, layout, { boxes, connectors }, { topLeft: origin })++ const all = [...layout.nodes.values()]+ const shift = {+ x: origin.x - Math.min(...all.map((rect) => rect.x)),+ y: origin.y - Math.min(...all.map((rect) => rect.y))+ }+ let bent = 0+ for (const [edgeId, connectorId] of connectors) {+ const route = expectDefined(layout.edges.get(edgeId))+ const corners = route.points+ .slice(1, -1)+ .map((point) => ({ x: point.x + shift.x, y: point.y + shift.y }))+ const drawn = expectDefined(connectorRoute(graph, expectDefined(graph.getNode(connectorId))))+ const drawnCorners = drawn.pieces.slice(1).map((piece) => piece.from)+ expect(drawnCorners).toEqual(corners)+ bent += corners.length+ }+ // A fan-out bends at least one of its edges.+ expect(bent).toBeGreaterThan(0)+ })+})diff --git a/packages/core/tests/layout/diagram/layout.test.ts b/packages/core/tests/layout/diagram/layout.test.tsnew file mode 100644index 000000000..22c685c4e--- /dev/null+++ b/packages/core/tests/layout/diagram/layout.test.ts@@ -0,0 +1,68 @@+import { describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { layoutDiagram, type DiagramInput } from '#core/layout/diagram'++const node = (id: string, group?: string) => ({ id, width: 120, height: 50, group })++describe('layoutDiagram', () => {+ test('routes every edge from the middle of the side it leaves by to the middle of the one it enters', async () => {+ const input: DiagramInput = {+ direction: 'TB',+ nodes: [node('a'), node('b'), node('c')],+ groups: [],+ edges: [+ { id: 'ab', from: 'a', to: 'b' },+ { id: 'ac', from: 'a', to: 'c' }+ ]+ }+ const layout = await layoutDiagram(input)+ for (const edge of input.edges) {+ const route = expectDefined(layout.edges.get(edge.id))+ const from = expectDefined(layout.nodes.get(edge.from))+ const to = expectDefined(layout.nodes.get(edge.to))+ expect([route.startSide, route.endSide]).toEqual(['BOTTOM', 'TOP'])+ expect(route.points[0]).toEqual({ x: from.x + from.width / 2, y: from.y + from.height })+ expect(route.points.at(-1)).toEqual({ x: to.x + to.width / 2, y: to.y })+ // Every corner is a right angle.+ for (const [i, point] of route.points.slice(1).entries()) {+ const previous = expectDefined(route.points[i])+ expect(point.x === previous.x || point.y === previous.y).toBe(true)+ }+ }+ })++ test('keeps the first node written first when edges loop back to it', async () => {+ const layout = await layoutDiagram({+ direction: 'LR',+ nodes: [node('start'), node('work', 'loop'), node('check', 'loop')],+ groups: [{ id: 'loop' }],+ edges: [+ { id: 'a', from: 'start', to: 'work' },+ { id: 'b', from: 'work', to: 'check' },+ { id: 'c', from: 'check', to: 'start' }+ ]+ })+ const start = expectDefined(layout.nodes.get('start'))+ const work = expectDefined(layout.nodes.get('work'))+ const loop = expectDefined(layout.groups.get('loop'))+ expect(start.x + start.width).toBeLessThan(work.x)+ expect(loop.x).toBeLessThanOrEqual(work.x)+ expect(loop.x + loop.width).toBeGreaterThanOrEqual(work.x + work.width)+ })++ test('leaves room along an edge for its label', async () => {+ const gap = async (label?: { width: number; height: number }) => {+ const layout = await layoutDiagram({+ direction: 'TB',+ nodes: [node('a'), node('b')],+ groups: [],+ edges: [{ id: 'e', from: 'a', to: 'b', label }]+ })+ const a = expectDefined(layout.nodes.get('a'))+ return expectDefined(layout.nodes.get('b')).y - (a.y + a.height)+ }+ expect(await gap({ width: 60, height: 40 })).toBeGreaterThanOrEqual((await gap()) + 40)+ })+})diff --git a/packages/core/tests/tools/create/mermaid.test.ts b/packages/core/tests/tools/create/mermaid.test.tsnew file mode 100644index 000000000..497cc2fa8--- /dev/null+++ b/packages/core/tests/tools/create/mermaid.test.ts@@ -0,0 +1,55 @@+import { describe, expect, test } from 'bun:test'++import * as v from 'valibot'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { importMermaid } from '@open-pencil/core/tools'+import { SceneGraph } from '@open-pencil/scene-graph'++const importedSchema = v.object({+ ids: v.array(v.string()),+ nodes: v.record(v.string(), v.string()),+ connectors: v.record(v.string(), v.string())+})++describe('import_mermaid', () => {+ test('returns the layer of every node and subgraph and the connector of every edge', async () => {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ const result = v.parse(+ importedSchema,+ await importMermaid.execute(figma, {+ mermaid:+ 'flowchart LR\n subgraph S [Steps]\n A[Plan] --> B[Build]\n end\n B --> C[Ship]'+ })+ )+ expect(Object.keys(result.nodes).sort()).toEqual(['A', 'B', 'C', 'S'])+ expect(graph.getNode(result.nodes.S ?? '')?.type).toBe('SECTION')+ expect(Object.keys(result.connectors)).toHaveLength(2)+ expect(result.ids.map((id) => graph.getNode(id)?.parentId)).toEqual(+ result.ids.map(() => figma.currentPage.id)+ )+ })++ test('places the diagram beside what the page already holds', async () => {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ const existing = figma.createRectangle()+ existing.resize(300, 200)+ const result = v.parse(+ importedSchema,+ await importMermaid.execute(figma, { mermaid: 'graph TD\n A --> B' })+ )+ const left = Math.min(...result.ids.map((id) => graph.getNode(id)?.x ?? 0))+ expect(left).toBeGreaterThan(300)+ })++ test('reports what Mermaid cannot read', async () => {+ const figma = new FigmaAPI(new SceneGraph())+ expect(await importMermaid.execute(figma, { mermaid: 'pie\n "a": 1' })).toEqual({+ error: 'Only Mermaid flowcharts, starting with `flowchart` or `graph`, are supported'+ })+ const broken = await importMermaid.execute(figma, { mermaid: 'flowchart LR\n A --> ' })+ expect(broken).toMatchObject({ error: expect.stringContaining('Parse error') })+ })+})diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.mdindex df15dcecd..d6385821c 100644--- a/packages/docs/programmable/cli/exporting.md+++ b/packages/docs/programmable/cli/exporting.md@@ -47,7 +47,7 @@ openpencil convert design.pen --font-policy strictRun [`openpencil fonts`](./inspecting#font-diagnostics) first to inspect affected faces. Export preparation may use configured font providers, so its result can differ from the offline file diagnostic.-`convert` loads fonts for `.pen` and draw.io files, which store layout intent rather than sizes: it lays them out again with their text measured in their own fonts before writing, so `strict` stops it before anything is written.+`convert` loads fonts for `.pen`, draw.io, and Mermaid files, which store layout intent rather than sizes: it lays them out again with their text measured in their own fonts before writing, so `strict` stops it before anything is written. A Mermaid flowchart (`.mmd` or `.mermaid`) is laid out as it is read, its text measured in the fonts it is drawn in.This policy does not apply to exports from the running app, or to SVG, PowerPoint, JSX, HTML, and `.fig` exports. It checks font resolution, not complete visual equivalence with Figma.diff --git a/packages/feedback/src/contract/schema.ts b/packages/feedback/src/contract/schema.tsindex 84319cd8a..5b7c99c62 100644--- a/packages/feedback/src/contract/schema.ts+++ b/packages/feedback/src/contract/schema.ts@@ -13,6 +13,7 @@ export const DOCUMENT_FORMATS = ['fig','pen','drawio',+ 'mermaid','png','jpg','webp',diff --git a/packages/mermaid/README.md b/packages/mermaid/README.mdnew file mode 100644index 000000000..1ba3aefd2--- /dev/null+++ b/packages/mermaid/README.md@@ -0,0 +1,5 @@+# @open-pencil/mermaid++Mermaid diagrams read into a typed model: flowcharts' nodes with their shapes and labels, edges with their arrowheads and strokes, subgraphs, and styles.++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 `@open-pencil/scene-graph`; laying diagrams out as design layers happens in `@open-pencil/core`.diff --git a/packages/mermaid/package.json b/packages/mermaid/package.jsonnew file mode 100644index 000000000..49d956e02--- /dev/null+++ b/packages/mermaid/package.json@@ -0,0 +1,48 @@+{+ "name": "@open-pencil/mermaid",+ "version": "0.16.0",+ "license": "MIT",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/open-pencil/open-pencil.git",+ "directory": "packages/mermaid"+ },+ "files": [+ "dist",+ "src",+ "README.md"+ ],+ "type": "module",+ "sideEffects": false,+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "bun": "./src/index.ts",+ "import": "./dist/index.js",+ "default": "./dist/index.js"+ }+ },+ "publishConfig": {+ "access": "public",+ "provenance": true+ },+ "scripts": {+ "build": "bunx tsdown --config tsdown.config.ts",+ "check": "bun run typecheck && bun run build",+ "prepack": "bun run build",+ "typecheck": "bunx tsc --noEmit -p tsconfig.json"+ },+ "dependencies": {+ "entities": "^8.0.0",+ "parse5": "^8.0.1",+ "valibot": "^1.5.0",+ "yaml": "^2.9.0"+ },+ "devDependencies": {+ "@types/bun": "^1.3.14",+ "tsdown": "^0.22.14",+ "typescript": "~5.8.3"+ }+}diff --git a/packages/mermaid/src/detect.ts b/packages/mermaid/src/detect.tsnew file mode 100644index 000000000..509af6d3e--- /dev/null+++ b/packages/mermaid/src/detect.ts@@ -0,0 +1,14 @@+import { prepareSource } from './source'++/** The Mermaid diagrams OpenPencil reads. */+export type MermaidDiagramType = 'flowchart'++/**+ * The kind of Mermaid diagram `text` holds, by its first keyword after any front matter,+ * directives, and comments, as Mermaid's detectors decide; null for a kind OpenPencil does not+ * read, or text that is not Mermaid.+ */+export function detectMermaidDiagram(text: string): MermaidDiagramType | null {+ const { code } = prepareSource(text)+ return /^\s*(?:graph|flowchart)\b/.test(code) ? 'flowchart' : null+}diff --git a/packages/mermaid/src/flowchart/builder.ts b/packages/mermaid/src/flowchart/builder.tsnew file mode 100644index 000000000..8b890db4b--- /dev/null+++ b/packages/mermaid/src/flowchart/builder.ts@@ -0,0 +1,418 @@+import * as v from 'valibot'+import { parse as parseYAML } from 'yaml'++import { readLabel, type GrammarText } from '../label'+import type {+ FlowArrowhead,+ FlowDirection,+ FlowEdge,+ FlowNode,+ FlowStroke,+ FlowSubgraph,+ Flowchart+} from './model'+import { bracketShape, shapeNamed } from './shapes'++/** An edge as the grammar describes it before its ends are known. */+interface GrammarLink {+ type: string+ stroke: string+ length?: number+ text?: GrammarText+ id?: string+}++/** A `direction` statement inside a subgraph, as the grammar lists it among the members. */+interface DirectionStatement {+ stmt: 'dir'+ value: string+}++const STROKES: Record<string, FlowStroke> = {+ normal: 'normal',+ thick: 'thick',+ dotted: 'dotted',+ invisible: 'invisible'+}++const ARROWHEADS: Record<string, FlowArrowhead> = {+ arrow_point: 'arrow',+ arrow_circle: 'circle',+ arrow_cross: 'cross',+ arrow_open: 'none'+}++/** The arrowhead a link's first character opens it with, as in `<-->` or `o--o`. */+const START_HEADS: Record<string, string> = {+ '<': 'arrow_point',+ x: 'arrow_cross',+ o: 'arrow_circle'+}++/** The arrowhead a link's last character closes it with, and the one that opens it as well. */+const END_HEADS = new Map([+ ['x', { type: 'arrow_cross', opening: 'x' }],+ ['>', { type: 'arrow_point', opening: '<' }],+ ['o', { type: 'arrow_circle', opening: 'o' }]+])++/** Mermaid's longest edge: more dashes than this count as this many. */+const MAX_EDGE_LENGTH = 10++function direction(text: string): FlowDirection {+ const dir = text.trim()+ if (dir.includes('<')) return 'RL'+ if (dir.includes('^')) return 'BT'+ if (dir.includes('>')) return 'LR'+ if (dir.includes('v')) return 'TB'+ if (dir === 'BT' || dir === 'LR' || dir === 'RL') return dir+ return 'TB'+}++function isDirectionStatement(item: unknown): item is DirectionStatement {+ return typeof item === 'object' && item !== null && 'stmt' in item && item.stmt === 'dir'+}++/** What `@{ … }` data sets that a node keeps; other keys, such as `icon`, are left out. */+const shapeDataSchema = v.looseObject({+ shape: v.optional(v.string()),+ label: v.optional(v.pipe(v.union([v.string(), v.number()]), v.toString())),+ labelType: v.optional(v.string())+})++type ShapeData = v.InferOutput<typeof shapeDataSchema>++/** `@{ … }` data, which is YAML, written as a flow mapping when it fits on one line. */+function shapeData(text: string): ShapeData {+ const data: unknown = parseYAML(text.includes('\n') ? `${text}\n` : `{\n${text}\n}`)+ const parsed = v.safeParse(shapeDataSchema, data)+ return parsed.success ? parsed.output : {}+}++function arrowheads(type: string): { startArrow: FlowArrowhead; endArrow: FlowArrowhead } {+ if (type.startsWith('double_')) {+ const head = ARROWHEADS[type.slice('double_'.length)] ?? 'arrow'+ return { startArrow: head, endArrow: head }+ }+ return { startArrow: 'none', endArrow: ARROWHEADS[type] ?? 'arrow' }+}++/**+ * The `yy` object Mermaid's flowchart grammar calls as it parses, building a `Flowchart`. It+ * keeps the meaning Mermaid's `FlowDB` gives each call in the pinned release (MIT, Copyright (c)+ * 2014 - 2022 Knut Sveidqvist), without what only Mermaid's renderer needs: DOM ids, click+ * callbacks, sanitizing for the page, and edge animation.+ */+export class FlowchartBuilder {+ private dir: FlowDirection = 'TB'+ private readonly nodes = new Map<string, FlowNode>()+ private readonly edges: FlowEdge[] = []+ private readonly subgraphs: FlowSubgraph[] = []+ private readonly classDefs = new Map<string, string[]>()+ private defaultEdgeStyle: string[] = []+ private subgraphCount = 0+ private firstGraphSeen = false+ private accessibleTitle?: string+ private accessibleDescription?: string++ readonly lex = {+ /** True for the first `graph`/`flowchart` keyword only; a later one is text. */+ firstGraph: () => {+ if (this.firstGraphSeen) return false+ this.firstGraphSeen = true+ return true+ }+ }++ /**+ * The calls the grammar makes, as the plain object it copies them from: JISON copies `yy`'s+ * enumerable properties into its own state, which leaves out a class's methods.+ */+ grammarCalls() {+ return {+ lex: this.lex,+ setDirection: this.setDirection.bind(this),+ setAccTitle: this.setAccTitle.bind(this),+ setAccDescription: this.setAccDescription.bind(this),+ addVertex: this.addVertex.bind(this),+ destructLink: this.destructLink.bind(this),+ addLink: this.addLink.bind(this),+ updateLinkInterpolate: this.updateLinkInterpolate.bind(this),+ updateLink: this.updateLink.bind(this),+ addClass: this.addClass.bind(this),+ setClass: this.setClass.bind(this),+ setLink: this.setLink.bind(this),+ setTooltip: this.setTooltip.bind(this),+ setClickEvent: this.setClickEvent.bind(this),+ addSubGraph: this.addSubGraph.bind(this)+ }+ }++ result(title?: string): Flowchart {+ // `style` and `class` statements naming a subgraph style the subgraph, though the grammar+ // reports them as nodes.+ const subgraphIds = new Set(this.subgraphs.map((subgraph) => subgraph.id))+ for (const subgraph of this.subgraphs) {+ const node = this.nodes.get(subgraph.id)+ if (!node) continue+ subgraph.styles.push(...node.styles)+ subgraph.classes.push(...node.classes)+ }+ return {+ direction: this.dir,+ nodes: [...this.nodes.values()].filter((node) => !subgraphIds.has(node.id)),+ edges: this.edges.map((edge) => ({+ ...edge,+ styles: [...this.defaultEdgeStyle, ...edge.styles]+ })),+ subgraphs: this.subgraphs,+ classDefs: this.classDefs,+ title,+ accessibleTitle: this.accessibleTitle,+ accessibleDescription: this.accessibleDescription+ }+ }++ setDirection(dir: string): void {+ this.dir = direction(dir)+ }++ setAccTitle(text: string): void {+ this.accessibleTitle = text+ }++ setAccDescription(text: string): void {+ this.accessibleDescription = text+ }++ addVertex(+ id: string,+ text?: GrammarText,+ type?: string,+ styles?: string[],+ classes?: string[],+ _dir?: string,+ _props?: Record<string, unknown>,+ metadata?: string+ ): void {+ if (!id || id.trim().length === 0) return+ const data = metadata === undefined ? undefined : shapeData(metadata)+ // An edge's id, or `@{ … }` after a subgraph's, names that edge or subgraph, not a node;+ // the data it carries is animation and the like, which nothing here draws.+ if (this.edges.some((edge) => edge.id === id) || (data && this.isSubgraph(id))) return+ let node = this.nodes.get(id)+ if (!node) {+ node = {+ id,+ label: { text: id, format: 'text' },+ shape: 'rect',+ classes: [],+ styles: []+ }+ this.nodes.set(id, node)+ }+ if (text) node.label = readLabel(text)+ if (type !== undefined) node.shape = bracketShape(type)+ if (styles) node.styles.push(...styles)+ if (classes) node.classes.push(...classes)+ if (!data) return+ if (typeof data.shape === 'string') {+ const shape = data.shape === data.shape.toLowerCase() ? shapeNamed(data.shape) : null+ if (!shape) throw new Error(`No such shape: ${data.shape}.`)+ node.shape = shape+ }+ if (typeof data.label === 'string') {+ node.label = readLabel({+ text: data.label,+ type: data.labelType === 'text' || data.labelType === 'string' ? 'text' : 'markdown'+ })+ }+ }++ destructLink(end: string, start?: string): GrammarLink {+ const info = this.endOfLink(end)+ if (!start) return info+ const begin = this.startOfLink(start)+ if (begin.stroke !== info.stroke) return { type: 'INVALID', stroke: 'INVALID' }+ if (begin.type === 'arrow_open') return { ...info, type: info.type }+ if (begin.type !== info.type) return { type: 'INVALID', stroke: 'INVALID' }+ return { ...info, type: `double_${begin.type}` }+ }++ addLink(starts: string[], ends: string[], link: GrammarLink): void {+ const id = link.id?.replace('@', '')+ for (const from of starts) {+ for (const to of ends) {+ // In `A e1@--> B & C`, the id names the edge from the last start to the first end.+ const named = from === starts.at(-1) && to === ends[0]+ this.addEdge(from, to, link, named ? id : undefined)+ }+ }+ }++ updateLinkInterpolate(): void {+ // Curve styles are Mermaid's renderer's; connectors take their own line type.+ }++ updateLink(positions: ('default' | number)[], styles: string[]): void {+ for (const position of positions) {+ if (position === 'default') {+ this.defaultEdgeStyle = styles+ continue+ }+ const edge = this.edges.at(position)+ if (!edge || position < 0) {+ throw new Error(+ `The index ${position} for linkStyle is out of bounds. Valid indices for linkStyle are between 0 and ${this.edges.length - 1}.`+ )+ }+ edge.styles = styles+ }+ }++ addClass(ids: string, styles: string[]): void {+ // Commas and semicolons separate declarations; an escaped comma, as in `font-family:a\,b`,+ // is part of one.+ const declarations = styles+ .join(',')+ .split(/(?<!\\)[,;]/)+ .map((declaration) => declaration.replaceAll('\\,', ','))+ for (const id of ids.split(',')) {+ const existing = this.classDefs.get(id) ?? []+ this.classDefs.set(id, [...existing, ...declarations])+ }+ }++ setClass(ids: string, className: string): void {+ for (const id of ids.split(',')) {+ const subgraph = this.subgraphs.find((candidate) => candidate.id === id)+ if (subgraph) subgraph.classes.push(className)+ else this.nodes.get(id)?.classes.push(className)+ }+ }++ setLink(ids: string, href: string, target?: string): void {+ for (const id of ids.split(',')) {+ const node = this.nodes.get(id)+ if (node) node.link = target ? { href, target } : { href }+ }+ }++ setTooltip(ids: string, tooltip?: string): void {+ if (tooltip === undefined) return+ for (const id of ids.split(',')) {+ const node = this.nodes.get(id)+ if (node) node.tooltip = tooltip+ }+ }++ setClickEvent(): void {+ // Callbacks run scripts on Mermaid's page; a design layer has none to run.+ }++ addSubGraph(+ idText: GrammarText | undefined,+ list: unknown[],+ titleText: GrammarText | undefined+ ): string {+ // `subgraph Some title` gives the title as the id too; an id with spaces is no id.+ let id = idText?.text.trim()+ if (idText && idText === titleText && /\s/.test(idText.text)) id = undefined+ let dir: FlowDirection | undefined+ const members: string[] = []+ for (const item of list.flat()) {+ if (isDirectionStatement(item)) {+ dir = direction(item.value)+ continue+ }+ if (typeof item !== 'string' || item.trim() === '' || members.includes(item)) continue+ members.push(item)+ }+ const subgraphId = id ?? `subGraph${this.subgraphCount}`+ this.subgraphCount+++ // A node belongs to the subgraph that closes first, which is the innermost one, and a+ // subgraph never holds itself.+ const own = members.filter(+ (member) =>+ member !== subgraphId &&+ !this.subgraphs.some((subgraph) => subgraph.members.includes(member))+ )+ const existing = this.subgraphs.find((subgraph) => subgraph.id === subgraphId)+ if (existing) {+ // A repeated id adds to the first declaration, which keeps its title and direction.+ existing.members.push(...own)+ return subgraphId+ }+ this.subgraphs.push({+ id: subgraphId,+ title: titleText ? readLabel(titleText) : { text: '', format: 'text' },+ members: own,+ direction: dir,+ classes: [],+ styles: []+ })+ return subgraphId+ }++ private isSubgraph(id: string): boolean {+ return this.subgraphs.some((subgraph) => subgraph.id === id)+ }++ private addEdge(from: string, to: string, link: GrammarLink, id?: string): void {+ const label = link.text && readLabel(link.text)+ const edgeId =+ id && !this.edges.some((edge) => edge.id === id)+ ? id+ : `L_${from}_${to}_${this.edges.filter((edge) => edge.from === from && edge.to === to).length}`+ this.edges.push({+ id: edgeId,+ from,+ to,+ ...(label && label.text !== '' ? { label } : {}),+ ...arrowheads(link.type),+ stroke: STROKES[link.stroke] ?? 'normal',+ length: Math.min(link.length ?? 1, MAX_EDGE_LENGTH),+ styles: []+ })+ }++ private startOfLink(text: string): { type: string; stroke: string } {+ let rest = text.trim()+ let type = 'arrow_open'+ const head = rest[0]+ const opening = head && START_HEADS[head]+ if (opening) {+ type = opening+ rest = rest.slice(1)+ }+ let stroke = 'normal'+ if (rest.includes('=')) stroke = 'thick'+ if (rest.includes('.')) stroke = 'dotted'+ return { type, stroke }+ }++ private endOfLink(text: string): GrammarLink {+ const link = text.trim()+ let line = link.slice(0, -1)+ let type = 'arrow_open'+ const tail = link.slice(-1)+ const head = END_HEADS.get(tail)+ if (head) {+ type = head.type+ if (link.startsWith(head.opening)) {+ type = `double_${type}`+ line = line.slice(1)+ }+ }+ let stroke = 'normal'+ let length = line.length - 1+ if (line.startsWith('=')) stroke = 'thick'+ if (line.startsWith('~')) stroke = 'invisible'+ const dots = line.split('.').length - 1+ if (dots) {+ stroke = 'dotted'+ length = dots+ }+ return { type, stroke, length }+ }+}diff --git a/packages/mermaid/src/flowchart/model.ts b/packages/mermaid/src/flowchart/model.tsnew file mode 100644index 000000000..927602b3c--- /dev/null+++ b/packages/mermaid/src/flowchart/model.ts@@ -0,0 +1,72 @@+import type { FlowShape } from './shapes'++/** The way a flowchart, or a subgraph inside one, lays its nodes out: top to bottom, and so on. */+export type FlowDirection = 'TB' | 'BT' | 'LR' | 'RL'++/** A label's text; `markdown` text came in backticks and may hold `**bold**` and `*italic*`. */+export interface FlowLabel {+ text: string+ format: 'text' | 'markdown'+}++export interface FlowNode {+ id: string+ label: FlowLabel+ shape: FlowShape+ /** Class names in the order they were given, `classDef` names among them. */+ classes: string[]+ /** CSS declarations from `style` statements, as written (`fill:#f9f`). */+ styles: string[]+ /** Where `click` sends a reader, with its target window when given. */+ link?: { href: string; target?: string }+ tooltip?: string+}++/** What an edge's end is drawn with. */+export type FlowArrowhead = 'none' | 'arrow' | 'circle' | 'cross'++/** How an edge's line is drawn: `-->`, `==>`, `-.->`, or `~~~`, which lays out but is not drawn. */+export type FlowStroke = 'normal' | 'thick' | 'dotted' | 'invisible'++export interface FlowEdge {+ id: string+ from: string+ to: string+ label?: FlowLabel+ startArrow: FlowArrowhead+ endArrow: FlowArrowhead+ stroke: FlowStroke+ /** How many ranks the edge spans at least: one more for each extra dash, dot, or equals sign. */+ length: number+ /** CSS declarations from `linkStyle`, the default ones first. */+ styles: string[]+}++export interface FlowSubgraph {+ id: string+ title: FlowLabel+ /** Ids of the nodes and subgraphs it holds, each in exactly one subgraph. */+ members: string[]+ /** Its own `direction`, when it sets one. */+ direction?: FlowDirection+ classes: string[]+ /** CSS declarations from `style` statements naming the subgraph. */+ styles: string[]+}++/** A Mermaid flowchart (`flowchart` or `graph`) as written, before anything lays it out. */+export interface Flowchart {+ direction: FlowDirection+ /** Nodes in the order they first appear. */+ nodes: FlowNode[]+ /** Edges in the order they appear, which is the order `linkStyle` numbers them in. */+ edges: FlowEdge[]+ /** Subgraphs in the order they close, so a subgraph comes after those inside it. */+ subgraphs: FlowSubgraph[]+ /** `classDef` declarations by class name; `default` applies to every node. */+ classDefs: Map<string, string[]>+ /** The front matter's `title`. */+ title?: string+ accessibleTitle?: string+ accessibleDescription?: string+}diff --git a/packages/mermaid/src/flowchart/parse.ts b/packages/mermaid/src/flowchart/parse.tsnew file mode 100644index 000000000..630e65cdf--- /dev/null+++ b/packages/mermaid/src/flowchart/parse.ts@@ -0,0 +1,19 @@+import { prepareSource } from '../source'+import flowParser from '../upstream/flow.js'+import { FlowchartBuilder } from './builder'+import type { Flowchart } from './model'++/**+ * A Mermaid flowchart (`flowchart …` or `graph …`) read into its model. Throws Mermaid's parse+ * error, which names the line and what was expected, when the text is not a flowchart.+ */+export function parseFlowchart(text: string): Flowchart {+ const { code, title } = prepareSource(text)+ const builder = new FlowchartBuilder()+ // The grammar keeps its state in `yy` and its own lexer, so each parse gets a fresh copy.+ const parser = Object.create(flowParser) as typeof flowParser+ parser.yy = builder.grammarCalls()+ // Mermaid drops spaces after a closing brace at a line's end, which its grammar trips over.+ parser.parse(code.replace(/}\s*\n/g, '}\n'))+ return builder.result(title)+}diff --git a/packages/mermaid/src/flowchart/shapes.ts b/packages/mermaid/src/flowchart/shapes.tsnew file mode 100644index 000000000..f5dbe5e8b--- /dev/null+++ b/packages/mermaid/src/flowchart/shapes.ts@@ -0,0 +1,105 @@+/**+ * Mermaid's flowchart shapes by their short names, with the other names `@{ shape: … }` accepts+ * for each, from `rendering-util/rendering-elements/shapes.ts` in the pinned Mermaid release+ * (MIT, Copyright (c) 2014 - 2022 Knut Sveidqvist). `bun run generate:mermaid-sources --check`+ * reports when a newer release changes that file.+ */+const SHAPE_NAMES = {+ rect: ['proc', 'process', 'rectangle', 'squareRect'],+ rounded: ['event', 'roundedRect'],+ stadium: ['terminal', 'pill'],+ 'fr-rect': ['subprocess', 'subproc', 'framed-rectangle', 'subroutine'],+ cyl: ['db', 'database', 'cylinder'],+ datastore: ['data-store'],+ folder: ['directory'],+ bucket: [],+ console: [],+ browser: [],+ person: [],+ circle: ['circ'],+ bang: [],+ cloud: [],+ diam: ['decision', 'diamond', 'question'],+ hex: ['hexagon', 'prepare'],+ 'lean-r': ['lean-right', 'in-out', 'lean_right'],+ 'lean-l': ['lean-left', 'out-in', 'lean_left'],+ 'trap-b': ['priority', 'trapezoid-bottom', 'trapezoid'],+ 'trap-t': ['manual', 'trapezoid-top', 'inv-trapezoid', 'inv_trapezoid'],+ 'dbl-circ': ['double-circle', 'doublecircle'],+ text: [],+ 'notch-rect': ['card', 'notched-rectangle'],+ 'lin-rect': ['lined-rectangle', 'lined-process', 'lin-proc', 'shaded-process'],+ 'sm-circ': ['start', 'small-circle', 'stateStart'],+ 'fr-circ': ['stop', 'framed-circle', 'stateEnd'],+ fork: ['join', 'forkJoin'],+ hourglass: ['collate'],+ brace: ['comment', 'brace-l'],+ 'brace-r': [],+ braces: [],+ bolt: ['com-link', 'lightning-bolt'],+ doc: ['document'],+ delay: ['half-rounded-rectangle'],+ 'h-cyl': ['das', 'horizontal-cylinder'],+ 'lin-cyl': ['disk', 'lined-cylinder'],+ 'curv-trap': ['curved-trapezoid', 'display'],+ 'div-rect': ['div-proc', 'divided-rectangle', 'divided-process'],+ tri: ['extract', 'triangle'],+ 'win-pane': ['internal-storage', 'window-pane'],+ 'f-circ': ['junction', 'filled-circle'],+ 'notch-pent': ['loop-limit', 'notched-pentagon'],+ 'flip-tri': ['manual-file', 'flipped-triangle'],+ 'sl-rect': ['manual-input', 'sloped-rectangle'],+ docs: ['documents', 'st-doc', 'stacked-document'],+ 'st-rect': ['procs', 'processes', 'stacked-rectangle'],+ 'bow-rect': ['stored-data', 'bow-tie-rectangle'],+ 'cross-circ': ['summary', 'crossed-circle'],+ 'tag-doc': ['tagged-document'],+ 'tag-rect': ['tagged-rectangle', 'tag-proc', 'tagged-process'],+ flag: ['paper-tape'],+ odd: ['rect_left_inv_arrow'],+ 'lin-doc': ['lined-document']+} as const satisfies Record<string, readonly string[]>++/**+ * A flowchart node's shape, by Mermaid's short name for it, or `ellipse` for `A(-text-)`, which+ * Mermaid's grammar reads but its renderer refuses (mermaid-js/mermaid#5976).+ */+export type FlowShape = keyof typeof SHAPE_NAMES | 'ellipse'++const SHAPE_BY_NAME = new Map<string, FlowShape>(+ Object.entries(SHAPE_NAMES).flatMap(([shape, aliases]) =>+ [shape, ...aliases].map((name) => [name, shape as FlowShape] as const)+ )+)++/** The shape a name from `@{ shape: … }` stands for, or null for one Mermaid does not know. */+export function shapeNamed(name: string): FlowShape | null {+ return SHAPE_BY_NAME.get(name) ?? null+}++/**+ * The shape each bracket form stands for, by the vertex type Mermaid's grammar gives it: `[ ]` a+ * rectangle, `( )` a rounded one, `([ ])` a stadium, and so on.+ */+const BRACKET_SHAPES: Record<string, FlowShape> = {+ square: 'rect',+ rect: 'rect',+ round: 'rounded',+ ellipse: 'ellipse',+ stadium: 'stadium',+ subroutine: 'fr-rect',+ cylinder: 'cyl',+ circle: 'circle',+ doublecircle: 'dbl-circ',+ diamond: 'diam',+ hexagon: 'hex',+ odd: 'odd',+ trapezoid: 'trap-b',+ inv_trapezoid: 'trap-t',+ lean_right: 'lean-r',+ lean_left: 'lean-l'+}++export function bracketShape(vertexType: string): FlowShape {+ return BRACKET_SHAPES[vertexType] ?? 'rect'+}diff --git a/packages/mermaid/src/index.ts b/packages/mermaid/src/index.tsnew file mode 100644index 000000000..1ef3bd434--- /dev/null+++ b/packages/mermaid/src/index.ts@@ -0,0 +1,13 @@+export { detectMermaidDiagram, type MermaidDiagramType } from './detect'+export type {+ FlowArrowhead,+ FlowDirection,+ FlowEdge,+ FlowLabel,+ FlowNode,+ FlowStroke,+ FlowSubgraph,+ Flowchart+} from './flowchart/model'+export { parseFlowchart } from './flowchart/parse'+export type { FlowShape } from './flowchart/shapes'diff --git a/packages/mermaid/src/label.ts b/packages/mermaid/src/label.tsnew file mode 100644index 000000000..5f9231750--- /dev/null+++ b/packages/mermaid/src/label.ts@@ -0,0 +1,37 @@+import { decodeHTML } from 'entities'+import { parseFragment, type DefaultTreeAdapterTypes } from 'parse5'++import type { FlowLabel } from './flowchart/model'+import { decodeEntities } from './upstream/preprocess'++/** A label as Mermaid's grammar hands it over: its text, and how that text is to be read. */+export interface GrammarText {+ text: string+ type: string+}++type HTMLNode = DefaultTreeAdapterTypes.ChildNode++/** The text HTML shows: its text nodes, and a line break for each `<br>`. */+function shownText(nodes: HTMLNode[]): string {+ return nodes+ .map((node) => {+ if (node.nodeName === '#text' && 'value' in node) return node.value+ if (node.nodeName === 'br') return '\n'+ return 'childNodes' in node ? shownText(node.childNodes) : ''+ })+ .join('')+}++/**+ * A label's text as plain text and its format. Mermaid draws a label as HTML, so its tags only+ * style the text, `<br>` breaks the line, and entities stand for characters. Markdown, written+ * in backticks, keeps its marks for whoever draws it.+ */+export function readLabel(label: GrammarText): FlowLabel {+ let text = decodeEntities(label.text.trim())+ // Mermaid drops the quotes around a label written in them.+ if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) text = text.slice(1, -1)+ if (label.type === 'markdown') return { text: decodeHTML(text), format: 'markdown' }+ return { text: shownText(parseFragment(text).childNodes), format: 'text' }+}diff --git a/packages/mermaid/src/source.ts b/packages/mermaid/src/source.tsnew file mode 100644index 000000000..da692c7e8--- /dev/null+++ b/packages/mermaid/src/source.ts@@ -0,0 +1,51 @@+import * as v from 'valibot'+import { parse as parseYAML } from 'yaml'++import { cleanupComments } from './upstream/comments'+import { cleanupText, encodeEntities, removeDirectives } from './upstream/preprocess'+import { matchFrontMatter } from './upstream/regexes'++/** Mermaid source as a diagram's grammar reads it, and the title its front matter gives. */+export interface PreparedSource {+ code: string+ title?: string+}++/** The front matter OpenPencil reads: the title, which YAML may give as a number or a flag. */+const frontMatterSchema = v.looseObject({+ title: v.optional(v.pipe(v.union([v.string(), v.number(), v.boolean()]), v.toString()))+})++function frontMatterTitle(body: string): string | undefined {+ try {+ const parsed = v.safeParse(frontMatterSchema, parseYAML(body))+ return parsed.success ? parsed.output.title : undefined+ } catch {+ return undefined+ }+}++/**+ * Prepares Mermaid source as Mermaid does before its grammar reads it (`preprocessDiagram`, then+ * `Diagram.fromText`), with the functions copied from the pinned release: line endings and HTML+ * attributes cleaned up, front matter, directives, and comments taken out, and `#name;` entities+ * hidden from the grammar, which reads `;` as a statement break.+ */+export function prepareSource(text: string): PreparedSource {+ let code = cleanupText(text)+ let title: string | undefined+ const frontMatter = matchFrontMatter(code)+ if (frontMatter) {+ // Mermaid dedents front matter by its fences' indent before reading it.+ const { indent } = frontMatter+ const body = indent+ ? frontMatter.body+ .split('\n')+ .map((line) => (line.startsWith(indent) ? line.slice(indent.length) : line))+ .join('\n')+ : frontMatter.body+ title = frontMatterTitle(body)+ code = code.slice(frontMatter.length)+ }+ return { code: `${encodeEntities(cleanupComments(removeDirectives(code)))}\n`, title }+}diff --git a/packages/mermaid/src/upstream/MERMAID-LICENSE.txt b/packages/mermaid/src/upstream/MERMAID-LICENSE.txtnew file mode 100644index 000000000..2e5daebd2--- /dev/null+++ b/packages/mermaid/src/upstream/MERMAID-LICENSE.txt@@ -0,0 +1,21 @@+The MIT License (MIT)++Copyright (c) 2014 - 2022 Knut Sveidqvist++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/mermaid/src/upstream/comments.ts b/packages/mermaid/src/upstream/comments.tsnew file mode 100644index 000000000..aaccaac0c--- /dev/null+++ b/packages/mermaid/src/upstream/comments.ts@@ -0,0 +1,13 @@+// @ts-nocheck+// Copied by `bun run generate:mermaid-sources` from [email protected]+// (https://raw.githubusercontent.com/mermaid-js/mermaid/1fb7869866dd619168d840291c9c54b4f129758b/packages/mermaid/src/diagram-api/comments.ts)+// Copyright (c) 2014 - 2022 Knut Sveidqvist. MIT License; see MERMAID-LICENSE.txt.+// Do not edit: change the pinned release in tools/generate/mermaid-sources and regenerate.+/**+ * Remove all lines starting with `%%` from the text that don't contain a `%%{`+ * @param text - The text to remove comments from+ * @returns cleaned text+ */+export const cleanupComments = (text: string): string => {+ return text.replace(/^\s*%%(?!{)[^\n]+\n?/gm, '').trimStart();+};diff --git a/packages/mermaid/src/upstream/flow.d.ts b/packages/mermaid/src/upstream/flow.d.tsnew file mode 100644index 000000000..9d233d3a4--- /dev/null+++ b/packages/mermaid/src/upstream/flow.d.ts@@ -0,0 +1,8 @@+/** Mermaid's flowchart parser, generated from `flow.jison`; see `flow.js`. */+interface GeneratedParser {+ yy: object+ parse(text: string): unknown+}++declare const parser: GeneratedParser+export default parserdiff --git a/packages/mermaid/src/upstream/flow.jison b/packages/mermaid/src/upstream/flow.jisonnew file mode 100644index 000000000..2bf05309c--- /dev/null+++ b/packages/mermaid/src/upstream/flow.jison@@ -0,0 +1,635 @@+/** mermaid+ * https://mermaidjs.github.io/+ * (c) 2015 Knut Sveidqvist+ * MIT license.+ */++/* lexical grammar */+%lex+%x string+%x md_string+%x acc_title+%x acc_descr+%x acc_descr_multiline+%x dir+%x vertex+%x text+%x ellipseText+%x trapText+%x edgeText+%x thickEdgeText+%x dottedEdgeText+%x click+%x href+%x callbackname+%x callbackargs+%x shapeData+%x shapeDataStr+%x shapeDataEndBracket++%%+accTitle\s*":"\s* { this.begin("acc_title");return 'acc_title'; }+<acc_title>(?!\n|;|#)*[^\n]* { this.popState(); return "acc_title_value"; }+accDescr\s*":"\s* { this.begin("acc_descr");return 'acc_descr'; }+<acc_descr>(?!\n|;|#)*[^\n]* { this.popState(); return "acc_descr_value"; }+accDescr\s*"{"\s* { this.begin("acc_descr_multiline");}+<acc_descr_multiline>[\}] { this.popState(); }+<acc_descr_multiline>[^\}]* return "acc_descr_multiline_value";+// <acc_descr_multiline>.*[^\n]* { return "acc_descr_line"}+++\@\{ {+ // console.log('=> shapeData', yytext);+ this.pushState("shapeData"); yytext=""; return 'SHAPE_DATA' }+<shapeData>["] {+ // console.log('=> shapeDataStr', yytext);+ this.pushState("shapeDataStr");+ return 'SHAPE_DATA';+ }+<shapeDataStr>["] {+ // console.log('shapeData <==', yytext);+ this.popState(); return 'SHAPE_DATA'}+<shapeDataStr>[^\"]+ {+ // console.log('shapeData', yytext);+ const re = /\n\s*/g;+ yytext = yytext.replace(re,"<br/>");+ return 'SHAPE_DATA'}+<shapeData>[^}^"]+ {+ // console.log('shapeData', yytext);+ return 'SHAPE_DATA';+ }+<shapeData>"}" {+ // console.log('<== root', yytext)+ this.popState();+ }++/*+---interactivity command---+'call' adds a callback to the specified node. 'call' can only be specified when+the line was introduced with 'click'.+'call <callbackname>(<args>)' attaches the function 'callbackname' with the specified+arguments to the node that was specified by 'click'.+Function arguments are optional: 'call <callbackname>()' simply executes 'callbackname' without any arguments.+*/+"call"[\s]+ this.begin("callbackname");+<callbackname>\([\s]*\) this.popState();+<callbackname>\( this.popState(); this.begin("callbackargs");+<callbackname>[^(]* return 'CALLBACKNAME';+<callbackargs>\) this.popState();+<callbackargs>[^)]* return 'CALLBACKARGS';+++<md_string>[^`"]+ { return "MD_STR";}+<md_string>[`]["] { this.popState();}+<*>["][`] { this.begin("md_string");}+<string>[^"]+ { return "STR"; }+<string>["] this.popState();+<*>["] this.pushState("string");+"style" return 'STYLE';+"default" return 'DEFAULT';+"linkStyle" return 'LINKSTYLE';+"interpolate" return 'INTERPOLATE';+"classDef" return 'CLASSDEF';+"class" return 'CLASS';++++/*+---interactivity command---+'href' adds a link to the specified node. 'href' can only be specified when the+line was introduced with 'click'.+'href "<link>"' attaches the specified link to the node that was specified by 'click'.+*/+"href"[\s] return 'HREF';+++/*+'click' is the keyword to introduce a line that contains interactivity commands.+'click' must be followed by an existing node-id. All commands are attached to+that id.+'click <id>' can be followed by href or call commands in any desired order+*/+"click"[\s]+ this.begin("click");+<click>[\s\n] this.popState();+<click>[^\s\n]* return 'CLICK';++"flowchart-elk" {if(yy.lex.firstGraph()){this.begin("dir");} return 'GRAPH';}+"swimlane-beta" {if(yy.lex.firstGraph()){this.begin("dir");} return 'GRAPH';}+"graph" {if(yy.lex.firstGraph()){this.begin("dir");} return 'GRAPH';}+"flowchart" {if(yy.lex.firstGraph()){this.begin("dir");} return 'GRAPH';}+"subgraph" return 'subgraph';+"end"\b\s* return 'end';++"_self" return 'LINK_TARGET';+"_blank" return 'LINK_TARGET';+"_parent" return 'LINK_TARGET';+"_top" return 'LINK_TARGET';++<dir>(\r?\n)*\s*\n { this.popState(); return 'NODIR'; }+<dir>\s*"LR" { this.popState(); return 'DIR'; }+<dir>\s*"RL" { this.popState(); return 'DIR'; }+<dir>\s*"TB" { this.popState(); return 'DIR'; }+<dir>\s*"BT" { this.popState(); return 'DIR'; }+<dir>\s*"TD" { this.popState(); return 'DIR'; }+<dir>\s*"BR" { this.popState(); return 'DIR'; }+<dir>\s*"<" { this.popState(); return 'DIR'; }+<dir>\s*">" { this.popState(); return 'DIR'; }+<dir>\s*"^" { this.popState(); return 'DIR'; }+<dir>\s*"v" { this.popState(); return 'DIR'; }++.*direction\s+TB[^\n]* return 'direction_tb';+.*direction\s+BT[^\n]* return 'direction_bt';+.*direction\s+RL[^\n]* return 'direction_rl';+.*direction\s+LR[^\n]* return 'direction_lr';+.*direction\s+TD[^\n]* return 'direction_td';++[^\s\"]+\@(?=[^\{\"]) { return 'LINK_ID'; }+[0-9]+ return 'NUM';+\# return 'BRKT';+":::" return 'STYLE_SEPARATOR';+":" return 'COLON';+"&" return 'AMP';+";" return 'SEMI';+"," return 'COMMA';+"*" return 'MULT';++<INITIAL,edgeText>\s*[xo<]?\-\-+[-xo>]\s* { this.popState(); return 'LINK'; }+<INITIAL>\s*[xo<]?\-\-\s* { this.pushState("edgeText"); return 'START_LINK'; }+<edgeText>[^-]|\-(?!\-)+ return 'EDGE_TEXT';++<INITIAL,thickEdgeText>\s*[xo<]?\=\=+[=xo>]\s* { this.popState(); return 'LINK'; }+<INITIAL>\s*[xo<]?\=\=\s* { this.pushState("thickEdgeText"); return 'START_LINK'; }+<thickEdgeText>[^=]|\=(?!=) return 'EDGE_TEXT';++<INITIAL,dottedEdgeText>\s*[xo<]?\-?\.+\-[xo>]?\s* { this.popState(); return 'LINK'; }+<INITIAL>\s*[xo<]?\-\.\s* { this.pushState("dottedEdgeText"); return 'START_LINK'; }+<dottedEdgeText>[^\.]|\.(?!-) return 'EDGE_TEXT';+++<*>\s*\~\~[\~]+\s* return 'LINK';++<ellipseText>[-/\)][\)] { this.popState(); return '-)'; }+<ellipseText>[^\(\)\[\]\{\}]|-\!\)+ return "TEXT"+<*>"(-" { this.pushState("ellipseText"); return '(-'; }++<text>"])" { this.popState(); return 'STADIUMEND'; }+<*>"([" { this.pushState("text"); return 'STADIUMSTART'; }++<text>"]]" { this.popState(); return 'SUBROUTINEEND'; }+<*>"[[" { this.pushState("text"); return 'SUBROUTINESTART'; }++"[|" { return 'VERTEX_WITH_PROPS_START'; }++\> { this.pushState("text"); return 'TAGEND'; }++<text>")]" { this.popState(); return 'CYLINDEREND'; }+<*>"[(" { this.pushState("text") ;return 'CYLINDERSTART'; }++<text>")))" { this.popState(); return 'DOUBLECIRCLEEND'; }+<*>"(((" { this.pushState("text"); return 'DOUBLECIRCLESTART'; }++<trapText>[\\(?=\])][\]] { this.popState(); return 'TRAPEND'; }+<trapText>\/(?=\])\] { this.popState(); return 'INVTRAPEND'; }+<trapText>\/(?!\])|\\(?!\])|[^\\\[\]\(\)\{\}\/]+ return 'TEXT';+<*>"[/" { this.pushState("trapText"); return 'TRAPSTART'; }++<*>"[\\" { this.pushState("trapText"); return 'INVTRAPSTART'; }+++"<" return 'TAGSTART';+">" return 'TAGEND';+"^" return 'UP';+"\|" return 'SEP';+"v" return 'DOWN';+"*" return 'MULT';+"#" return 'BRKT';+"&" return 'AMP';+([A-Za-z0-9!"\#$%&'*+\.`?\\_\/]|\-(?=[^\>\-\.])|=(?!=))+ {+ return 'NODE_STRING';+}+"-" return 'MINUS'+[\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]|+[\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]|+[\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5]|+[\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA]|+[\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE]|+[\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA]|+[\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0]|+[\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977]|+[\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2]|+[\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A]|+[\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39]|+[\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8]|+[\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C]|+[\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C]|+[\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99]|+[\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0]|+[\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D]|+[\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3]|+[\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10]|+[\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1]|+[\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81]|+[\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3]|+[\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6]|+[\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A]|+[\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081]|+[\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D]|+[\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0]|+[\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310]|+[\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C]|+[\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711]|+[\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7]|+[\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C]|+[\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16]|+[\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF]|+[\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC]|+[\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D]|+[\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D]|+[\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3]|+[\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F]|+[\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128]|+[\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184]|+[\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3]|+[\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6]|+[\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE]|+[\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C]|+[\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D]|+[\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC]|+[\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B]|+[\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788]|+[\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805]|+[\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB]|+[\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28]|+[\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5]|+[\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4]|+[\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E]|+[\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D]|+[\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36]|+[\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D]|+[\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC]|+[\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF]|+[\uFFD2-\uFFD7\uFFDA-\uFFDC]+ return 'UNICODE_TEXT';++<text>"|" { this.popState(); return 'PIPE'; }+<*>"|" { this.pushState("text"); return 'PIPE'; }++<text>")" { this.popState(); return 'PE'; }+<*>"(" { this.pushState("text"); return 'PS'; }++<text>"]" { this.popState(); return 'SQE'; }+<*>"[" { this.pushState("text"); return 'SQS'; }++<text>(\}) { this.popState(); return 'DIAMOND_STOP' }+<*>"{" { this.pushState("text"); return 'DIAMOND_START' }+<text>[^\[\]\(\)\{\}\|\"]+ return "TEXT";++"\"" return 'QUOTE';+(\r?\n)+ return 'NEWLINE';+[^\S\n\r]+ return 'SPACE';+<<EOF>> return 'EOF';++/lex++/* operator associations and precedence */++%left '^'++%start start++%% /* language grammar */++start+ : graphConfig document+ ;+++document+ : /* empty */+ { $$ = [];}+ | document line+ {+ if(!Array.isArray($line) || $line.length > 0){+ $document.push($line);+ }+ $$=$document;}+ ;++line+ : statement+ {$$=$statement;}+ | SEMI+ | NEWLINE+ | SPACE+ | EOF+ ;++graphConfig+ : SPACE graphConfig+ | NEWLINE graphConfig+ | GRAPH NODIR+ { yy.setDirection('TB');$$ = 'TB';}+ | GRAPH DIR FirstStmtSeparator+ { yy.setDirection($DIR);$$ = $DIR;}+ // | GRAPH SPACE TAGEND FirstStmtSeparator+ // { yy.setDirection("LR");$$ = $TAGEND;}+ // | GRAPH SPACE TAGSTART FirstStmtSeparator+ // { yy.setDirection("RL");$$ = $TAGSTART;}+ // | GRAPH SPACE UP FirstStmtSeparator+ // { yy.setDirection("BT");$$ = $UP;}+ // | GRAPH SPACE DOWN FirstStmtSeparator+ // { yy.setDirection("TB");$$ = $DOWN;}+ ;++ending: endToken ending+ | endToken+ ;++endToken: NEWLINE | SPACE | EOF;++FirstStmtSeparator+ : SEMI | NEWLINE | spaceList NEWLINE ;+++spaceListNewline+ : SPACE spaceListNewline+ | NEWLINE spaceListNewline+ | NEWLINE+ | SPACE+ ;+++spaceList+ : SPACE spaceList+ | SPACE+ ;++statement+ : vertexStatement separator+ { $$=$vertexStatement.nodes}+ | styleStatement separator+ {$$=[];}+ | linkStyleStatement separator+ {$$=[];}+ | classDefStatement separator+ {$$=[];}+ | classStatement separator+ {$$=[];}+ | clickStatement separator+ {$$=[];}+ | subgraph SPACE textNoTags SQS text SQE separator document end+ {$$=yy.addSubGraph($textNoTags,$document,$text);}+ | subgraph SPACE textNoTags separator document end+ {$$=yy.addSubGraph($textNoTags,$document,$textNoTags);}+ // | subgraph SPACE textNoTags separator document end+ // {$$=yy.addSubGraph($textNoTags,$document,$textNoTags);}+ | subgraph separator document end+ {$$=yy.addSubGraph(undefined,$document,undefined);}+ | direction+ | acc_title acc_title_value { $$=$acc_title_value.trim();yy.setAccTitle($$); }+ | acc_descr acc_descr_value { $$=$acc_descr_value.trim();yy.setAccDescription($$); }+ | acc_descr_multiline_value { $$=$acc_descr_multiline_value.trim();yy.setAccDescription($$); }+ ;++separator: NEWLINE | SEMI | EOF ;++shapeData:+ shapeData SHAPE_DATA+ { $$ = $1 + $2; }+ | SHAPE_DATA+ { $$ = $1; }+ ;++vertexStatement: vertexStatement link node shapeData+ { /* console.warn('vs shapeData',$vertexStatement.stmt,$node, $shapeData);*/ yy.addVertex($node[$node.length-1],undefined,undefined,undefined, undefined,undefined, undefined,$shapeData); yy.addLink($vertexStatement.stmt,$node,$link); $$ = { stmt: $node, nodes: $node.concat($vertexStatement.nodes) } }+ | vertexStatement link node+ { /*console.warn('vs',$vertexStatement.stmt,$node);*/ yy.addLink($vertexStatement.stmt,$node,$link); $$ = { stmt: $node, nodes: $node.concat($vertexStatement.nodes) } }+ | vertexStatement link node spaceList+ { /* console.warn('vs',$vertexStatement.stmt,$node); */ yy.addLink($vertexStatement.stmt,$node,$link); $$ = { stmt: $node, nodes: $node.concat($vertexStatement.nodes) } }+ |node spaceList { /*console.warn('vertexStatement: node spaceList', $node);*/ $$ = {stmt: $node, nodes:$node }}+ |node shapeData {+ /*console.warn('vertexStatement: node shapeData', $node[0], $shapeData);*/+ yy.addVertex($node[$node.length-1],undefined,undefined,undefined, undefined,undefined, undefined,$shapeData);+ $$ = {stmt: $node, nodes:$node, shapeData: $shapeData}+ }+ |node { /* console.warn('vertexStatement: single node', $node); */ $$ = {stmt: $node, nodes:$node }}+ ;++node: styledVertex+ { /*console.warn('nod', $styledVertex);*/ $$ = [$styledVertex];}+ | node shapeData spaceList AMP spaceList styledVertex+ { yy.addVertex($node[$node.length-1],undefined,undefined,undefined, undefined,undefined, undefined,$shapeData); $$ = $node.concat($styledVertex); /*console.warn('pip2', $node[0], $styledVertex, $$);*/ }+ | node spaceList AMP spaceList styledVertex+ { $$ = $node.concat($styledVertex); /*console.warn('pip', $node[0], $styledVertex, $$);*/ }+ ;++styledVertex: vertex+ { /* console.warn('nodc', $vertex);*/ $$ = $vertex;}+ | vertex STYLE_SEPARATOR idString+ {$$ = $vertex;yy.setClass($vertex,$idString)}+ ;++vertex: idString SQS text SQE+ {$$ = $idString;yy.addVertex($idString,$text,'square');}+ | idString DOUBLECIRCLESTART text DOUBLECIRCLEEND+ {$$ = $idString;yy.addVertex($idString,$text,'doublecircle');}+ | idString PS PS text PE PE+ {$$ = $idString;yy.addVertex($idString,$text,'circle');}+ | idString '(-' text '-)'+ {$$ = $idString;yy.addVertex($idString,$text,'ellipse');}+ | idString STADIUMSTART text STADIUMEND+ {$$ = $idString;yy.addVertex($idString,$text,'stadium');}+ | idString SUBROUTINESTART text SUBROUTINEEND+ {$$ = $idString;yy.addVertex($idString,$text,'subroutine');}+ | idString VERTEX_WITH_PROPS_START NODE_STRING\[field] COLON NODE_STRING\[value] PIPE text SQE+ {$$ = $idString;yy.addVertex($idString,$text,'rect',undefined,undefined,undefined, Object.fromEntries([[$field, $value]]));}+ | idString CYLINDERSTART text CYLINDEREND+ {$$ = $idString;yy.addVertex($idString,$text,'cylinder');}+ | idString PS text PE+ {$$ = $idString;yy.addVertex($idString,$text,'round');}+ | idString DIAMOND_START text DIAMOND_STOP+ {$$ = $idString;yy.addVertex($idString,$text,'diamond');}+ | idString DIAMOND_START DIAMOND_START text DIAMOND_STOP DIAMOND_STOP+ {$$ = $idString;yy.addVertex($idString,$text,'hexagon');}+ | idString TAGEND text SQE+ {$$ = $idString;yy.addVertex($idString,$text,'odd');}+ | idString TRAPSTART text TRAPEND+ {$$ = $idString;yy.addVertex($idString,$text,'trapezoid');}+ | idString INVTRAPSTART text INVTRAPEND+ {$$ = $idString;yy.addVertex($idString,$text,'inv_trapezoid');}+ | idString TRAPSTART text INVTRAPEND+ {$$ = $idString;yy.addVertex($idString,$text,'lean_right');}+ | idString INVTRAPSTART text TRAPEND+ {$$ = $idString;yy.addVertex($idString,$text,'lean_left');}+ | idString+ { /*console.warn('h: ', $idString);*/$$ = $idString;yy.addVertex($idString);}+ ;++++link: linkStatement arrowText+ {$linkStatement.text = $arrowText;$$ = $linkStatement;}+ | linkStatement TESTSTR SPACE+ {$linkStatement.text = $TESTSTR;$$ = $linkStatement;}+ | linkStatement arrowText SPACE+ {$linkStatement.text = $arrowText;$$ = $linkStatement;}+ | linkStatement+ {$$ = $linkStatement;}+ | START_LINK edgeText LINK+ {var inf = yy.destructLink($LINK, $START_LINK); $$ = {"type":inf.type,"stroke":inf.stroke,"length":inf.length,"text":$edgeText};}+ | LINK_ID START_LINK edgeText LINK+ {var inf = yy.destructLink($LINK, $START_LINK); $$ = {"type":inf.type,"stroke":inf.stroke,"length":inf.length,"text":$edgeText, "id": $LINK_ID};}+ ;++edgeText: edgeTextToken+ {$$={text:$edgeTextToken, type:'text'};}+ | edgeText edgeTextToken+ {$$={text:$edgeText.text+''+$edgeTextToken, type:$edgeText.type};}+ |STR+ {$$={text: $STR, type: 'string'};}+ | MD_STR+ {$$={text:$MD_STR, type:'markdown'};}+ ;+++linkStatement: LINK+ {var inf = yy.destructLink($LINK);$$ = {"type":inf.type,"stroke":inf.stroke,"length":inf.length};}+ | LINK_ID LINK+ {var inf = yy.destructLink($LINK);$$ = {"type":inf.type,"stroke":inf.stroke,"length":inf.length, "id": $LINK_ID};}+ ;++arrowText:+ PIPE text PIPE+ {$$ = $text;}+ ;++text: textToken+ { $$={text:$textToken, type: 'text'};}+ | text textToken+ { $$={text:$text.text+''+$textToken, type: $text.type};}+ | STR+ { $$ = {text: $STR, type: 'string'};}+ | MD_STR+ { $$={text: $MD_STR, type: 'markdown'};}+ ;++++keywords+ : STYLE | LINKSTYLE | CLASSDEF | CLASS | CLICK | GRAPH | DIR | subgraph | end | DOWN | UP;+++textNoTags: textNoTagsToken+ {$$={text:$textNoTagsToken, type: 'text'};}+ | textNoTags textNoTagsToken+ {$$={text:$textNoTags.text+''+$textNoTagsToken, type: $textNoTags.type};}+ | STR+ { $$={text: $STR, type: 'text'};}+ | MD_STR+ { $$={text: $MD_STR, type: 'markdown'};}+ ;+++classDefStatement:CLASSDEF SPACE idString SPACE stylesOpt+ {$$ = $CLASSDEF;yy.addClass($idString,$stylesOpt);}+ ;++classStatement:CLASS SPACE idString\[vertex] SPACE idString\[class]+ {$$ = $CLASS;yy.setClass($vertex, $class);}+ ;++clickStatement+ : CLICK CALLBACKNAME {$$ = $CLICK;yy.setClickEvent($CLICK, $CALLBACKNAME);}+ | CLICK CALLBACKNAME SPACE STR {$$ = $CLICK;yy.setClickEvent($CLICK, $CALLBACKNAME);yy.setTooltip($CLICK, $STR);}+ | CLICK CALLBACKNAME CALLBACKARGS {$$ = $CLICK;yy.setClickEvent($CLICK, $CALLBACKNAME, $CALLBACKARGS);}+ | CLICK CALLBACKNAME CALLBACKARGS SPACE STR {$$ = $CLICK;yy.setClickEvent($CLICK, $CALLBACKNAME, $CALLBACKARGS);yy.setTooltip($CLICK, $STR);}+ | CLICK HREF STR {$$ = $CLICK;yy.setLink($CLICK, $STR);}+ | CLICK HREF STR SPACE STR {$$ = $CLICK;yy.setLink($CLICK, $STR1);yy.setTooltip($CLICK, $STR2);}+ | CLICK HREF STR SPACE LINK_TARGET {$$ = $CLICK;yy.setLink($CLICK, $STR, $LINK_TARGET);}+ | CLICK HREF STR\[link] SPACE STR\[tooltip] SPACE LINK_TARGET {$$ = $CLICK;yy.setLink($CLICK, $link, $LINK_TARGET);yy.setTooltip($CLICK, $tooltip);}+ | CLICK alphaNum {$$ = $CLICK;yy.setClickEvent($CLICK, $alphaNum);}+ | CLICK alphaNum SPACE STR {$$ = $CLICK;yy.setClickEvent($CLICK, $alphaNum);yy.setTooltip($CLICK, $STR);}+ | CLICK STR {$$ = $CLICK;yy.setLink($CLICK, $STR);}+ | CLICK STR\[link] SPACE STR\[tooltip] {$$ = $CLICK;yy.setLink($CLICK, $link);yy.setTooltip($CLICK, $tooltip);}+ | CLICK STR SPACE LINK_TARGET {$$ = $CLICK;yy.setLink($CLICK, $STR, $LINK_TARGET);}+ | CLICK STR\[link] SPACE STR\[tooltip] SPACE LINK_TARGET {$$ = $CLICK;yy.setLink($CLICK, $link, $LINK_TARGET);yy.setTooltip($CLICK, $tooltip);}+ ;++styleStatement:STYLE SPACE idString SPACE stylesOpt+ {$$ = $STYLE;yy.addVertex($idString,undefined,undefined,$stylesOpt);}+ ;++linkStyleStatement+ : LINKSTYLE SPACE DEFAULT SPACE stylesOpt+ {$$ = $LINKSTYLE;yy.updateLink([$DEFAULT],$stylesOpt);}+ | LINKSTYLE SPACE numList SPACE stylesOpt+ {$$ = $LINKSTYLE;yy.updateLink($numList,$stylesOpt);}+ | LINKSTYLE SPACE DEFAULT SPACE INTERPOLATE SPACE alphaNum SPACE stylesOpt+ {$$ = $LINKSTYLE;yy.updateLinkInterpolate([$DEFAULT],$alphaNum);yy.updateLink([$DEFAULT],$stylesOpt);}+ | LINKSTYLE SPACE numList SPACE INTERPOLATE SPACE alphaNum SPACE stylesOpt+ {$$ = $LINKSTYLE;yy.updateLinkInterpolate($numList,$alphaNum);yy.updateLink($numList,$stylesOpt);}+ | LINKSTYLE SPACE DEFAULT SPACE INTERPOLATE SPACE alphaNum+ {$$ = $LINKSTYLE;yy.updateLinkInterpolate([$DEFAULT],$alphaNum);}+ | LINKSTYLE SPACE numList SPACE INTERPOLATE SPACE alphaNum+ {$$ = $LINKSTYLE;yy.updateLinkInterpolate($numList,$alphaNum);}+ ;++numList: NUM+ {$$ = [$NUM]}+ | numList COMMA NUM+ {$numList.push($NUM);$$ = $numList;}+ ;++stylesOpt: style+ {$$ = [$style]}+ | stylesOpt COMMA style+ {$stylesOpt.push($style);$$ = $stylesOpt;}+ ;++style: styleComponent+ |style styleComponent+ {$$ = $style + $styleComponent;}+ ;++styleComponent: NUM | NODE_STRING| COLON | UNIT | SPACE | BRKT | STYLE | PCT ;++/* Token lists */+idStringToken : NUM | NODE_STRING | DOWN | MINUS | DEFAULT | COMMA | COLON | AMP | BRKT | MULT | UNICODE_TEXT;++textToken : TEXT | TAGSTART | TAGEND | UNICODE_TEXT;++textNoTagsToken: NUM | NODE_STRING | SPACE | MINUS | AMP | UNICODE_TEXT | COLON | MULT | BRKT | keywords | START_LINK ;++edgeTextToken : EDGE_TEXT | UNICODE_TEXT ;++alphaNumToken : NUM | UNICODE_TEXT | NODE_STRING | DIR | DOWN | MINUS | COMMA | COLON | AMP | BRKT | MULT;++idString+ :idStringToken+ {$$=$idStringToken}+ | idString idStringToken+ {$$=$idString+''+$idStringToken}+ ;++alphaNum+ : alphaNumToken+ {$$=$alphaNumToken;}+ | alphaNum alphaNumToken+ {$$=$alphaNum+''+$alphaNumToken;}+ ;+++direction+ : direction_tb+ { $$={stmt:'dir', value:'TB'};}+ | direction_bt+ { $$={stmt:'dir', value:'BT'};}+ | direction_rl+ { $$={stmt:'dir', value:'RL'};}+ | direction_lr+ { $$={stmt:'dir', value:'LR'};}+ | direction_td+ { $$={stmt:'dir', value:'TD'};}+ ;++%%diff --git a/packages/mermaid/src/upstream/flow.js b/packages/mermaid/src/upstream/flow.jsnew file mode 100644index 000000000..2bd3fc499--- /dev/null+++ b/packages/mermaid/src/upstream/flow.js@@ -0,0 +1,1099 @@+// @ts-nocheck+// Generated by `bun run generate:mermaid-sources` from [email protected]+// (https://raw.githubusercontent.com/mermaid-js/mermaid/1fb7869866dd619168d840291c9c54b4f129758b/packages/mermaid/src/diagrams/flowchart/parser/flow.jison)+// Copyright (c) 2014 - 2022 Knut Sveidqvist. MIT License; see MERMAID-LICENSE.txt.+// Do not edit: change the pinned release in tools/generate/mermaid-sources and regenerate.+/* parser generated by jison 0.4.18 */+/*+ Returns a Parser object of the following structure:++ Parser: {+ yy: {}+ }++ Parser.prototype: {+ yy: {},+ trace: function(),+ symbols_: {associative list: name ==> number},+ terminals_: {associative list: number ==> name},+ productions_: [...],+ performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$),+ table: [...],+ defaultActions: {...},+ parseError: function(str, hash),+ parse: function(input),++ lexer: {+ EOF: 1,+ parseError: function(str, hash),+ setInput: function(input),+ input: function(),+ unput: function(str),+ more: function(),+ less: function(n),+ pastInput: function(),+ upcomingInput: function(),+ showPosition: function(),+ test_match: function(regex_match_array, rule_index),+ next: function(),+ lex: function(),+ begin: function(condition),+ popState: function(),+ _currentRules: function(),+ topState: function(),+ pushState: function(condition),++ options: {+ ranges: boolean (optional: true ==> token location info will include a .range[] member)+ flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match)+ backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code)+ },++ performAction: function(yy, yy_, $avoiding_name_collisions, YY_START),+ rules: [...],+ conditions: {associative list: name ==> set},+ }+ }+++ token location info (@$, _$, etc.): {+ first_line: n,+ last_line: n,+ first_column: n,+ last_column: n,+ range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based)+ }+++ the parseError function receives a 'hash' object with these members for lexer and parser errors: {+ text: (matched text)+ token: (the produced terminal token, if any)+ line: (yylineno)+ }+ while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: {+ loc: (yylloc)+ expected: (string describing the set of expected tokens)+ recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error)+ }+*/+var parser = (function(){+var o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v);return o},$V0=[1,4],$V1=[1,3],$V2=[1,5],$V3=[1,8,9,10,11,27,34,36,38,44,60,84,85,86,87,88,89,102,105,106,109,111,114,115,116,121,122,123,124,125],$V4=[2,2],$V5=[1,13],$V6=[1,14],$V7=[1,15],$V8=[1,16],$V9=[1,23],$Va=[1,25],$Vb=[1,26],$Vc=[1,27],$Vd=[1,50],$Ve=[1,49],$Vf=[1,29],$Vg=[1,30],$Vh=[1,31],$Vi=[1,32],$Vj=[1,33],$Vk=[1,45],$Vl=[1,47],$Vm=[1,43],$Vn=[1,48],$Vo=[1,44],$Vp=[1,51],$Vq=[1,46],$Vr=[1,52],$Vs=[1,53],$Vt=[1,34],$Vu=[1,35],$Vv=[1,36],$Vw=[1,37],$Vx=[1,38],$Vy=[1,58],$Vz=[1,8,9,10,11,27,32,34,36,38,44,60,84,85,86,87,88,89,102,105,106,109,111,114,115,116,121,122,123,124,125],$VA=[1,62],$VB=[1,61],$VC=[1,63],$VD=[8,9,11,75,77,78],$VE=[1,79],$VF=[1,92],$VG=[1,97],$VH=[1,96],$VI=[1,93],$VJ=[1,89],$VK=[1,95],$VL=[1,91],$VM=[1,98],$VN=[1,94],$VO=[1,99],$VP=[1,90],$VQ=[8,9,10,11,40,75,77,78],$VR=[8,9,10,11,40,46,75,77,78],$VS=[8,9,10,11,29,40,44,46,48,50,52,54,56,58,60,63,65,67,68,70,75,77,78,89,102,105,106,109,111,114,115,116],$VT=[8,9,11,44,60,75,77,78,89,102,105,106,109,111,114,115,116],$VU=[44,60,89,102,105,106,109,111,114,115,116],$VV=[1,122],$VW=[1,123],$VX=[1,125],$VY=[1,124],$VZ=[44,60,62,74,89,102,105,106,109,111,114,115,116],$V_=[1,134],$V$=[1,148],$V01=[1,149],$V11=[1,150],$V21=[1,151],$V31=[1,136],$V41=[1,138],$V51=[1,142],$V61=[1,143],$V71=[1,144],$V81=[1,145],$V91=[1,146],$Va1=[1,147],$Vb1=[1,152],$Vc1=[1,153],$Vd1=[1,132],$Ve1=[1,133],$Vf1=[1,140],$Vg1=[1,135],$Vh1=[1,139],$Vi1=[1,137],$Vj1=[8,9,10,11,27,32,34,36,38,44,60,84,85,86,87,88,89,102,105,106,109,111,114,115,116,121,122,123,124,125],$Vk1=[1,155],$Vl1=[1,157],$Vm1=[8,9,11],$Vn1=[8,9,10,11,14,44,60,89,105,106,109,111,114,115,116],$Vo1=[1,177],$Vp1=[1,173],$Vq1=[1,174],$Vr1=[1,178],$Vs1=[1,175],$Vt1=[1,176],$Vu1=[77,116,119],$Vv1=[8,9,10,11,12,14,27,29,32,44,60,75,84,85,86,87,88,89,90,105,109,111,114,115,116],$Vw1=[10,106],$Vx1=[31,49,51,53,55,57,62,64,66,67,69,71,116,117,118],$Vy1=[1,248],$Vz1=[1,246],$VA1=[1,250],$VB1=[1,244],$VC1=[1,245],$VD1=[1,247],$VE1=[1,249],$VF1=[1,251],$VG1=[1,269],$VH1=[8,9,11,106],$VI1=[8,9,10,11,60,84,105,106,109,110,111,112];+var parser = {trace: function trace() {},+yy: {},+symbols_: {"error":2,"start":3,"graphConfig":4,"document":5,"line":6,"statement":7,"SEMI":8,"NEWLINE":9,"SPACE":10,"EOF":11,"GRAPH":12,"NODIR":13,"DIR":14,"FirstStmtSeparator":15,"ending":16,"endToken":17,"spaceList":18,"spaceListNewline":19,"vertexStatement":20,"separator":21,"styleStatement":22,"linkStyleStatement":23,"classDefStatement":24,"classStatement":25,"clickStatement":26,"subgraph":27,"textNoTags":28,"SQS":29,"text":30,"SQE":31,"end":32,"direction":33,"acc_title":34,"acc_title_value":35,"acc_descr":36,"acc_descr_value":37,"acc_descr_multiline_value":38,"shapeData":39,"SHAPE_DATA":40,"link":41,"node":42,"styledVertex":43,"AMP":44,"vertex":45,"STYLE_SEPARATOR":46,"idString":47,"DOUBLECIRCLESTART":48,"DOUBLECIRCLEEND":49,"PS":50,"PE":51,"(-":52,"-)":53,"STADIUMSTART":54,"STADIUMEND":55,"SUBROUTINESTART":56,"SUBROUTINEEND":57,"VERTEX_WITH_PROPS_START":58,"NODE_STRING[field]":59,"COLON":60,"NODE_STRING[value]":61,"PIPE":62,"CYLINDERSTART":63,"CYLINDEREND":64,"DIAMOND_START":65,"DIAMOND_STOP":66,"TAGEND":67,"TRAPSTART":68,"TRAPEND":69,"INVTRAPSTART":70,"INVTRAPEND":71,"linkStatement":72,"arrowText":73,"TESTSTR":74,"START_LINK":75,"edgeText":76,"LINK":77,"LINK_ID":78,"edgeTextToken":79,"STR":80,"MD_STR":81,"textToken":82,"keywords":83,"STYLE":84,"LINKSTYLE":85,"CLASSDEF":86,"CLASS":87,"CLICK":88,"DOWN":89,"UP":90,"textNoTagsToken":91,"stylesOpt":92,"idString[vertex]":93,"idString[class]":94,"CALLBACKNAME":95,"CALLBACKARGS":96,"HREF":97,"LINK_TARGET":98,"STR[link]":99,"STR[tooltip]":100,"alphaNum":101,"DEFAULT":102,"numList":103,"INTERPOLATE":104,"NUM":105,"COMMA":106,"style":107,"styleComponent":108,"NODE_STRING":109,"UNIT":110,"BRKT":111,"PCT":112,"idStringToken":113,"MINUS":114,"MULT":115,"UNICODE_TEXT":116,"TEXT":117,"TAGSTART":118,"EDGE_TEXT":119,"alphaNumToken":120,"direction_tb":121,"direction_bt":122,"direction_rl":123,"direction_lr":124,"direction_td":125,"$accept":0,"$end":1},+terminals_: {2:"error",8:"SEMI",9:"NEWLINE",10:"SPACE",11:"EOF",12:"GRAPH",13:"NODIR",14:"DIR",27:"subgraph",29:"SQS",31:"SQE",32:"end",34:"acc_title",35:"acc_title_value",36:"acc_descr",37:"acc_descr_value",38:"acc_descr_multiline_value",40:"SHAPE_DATA",44:"AMP",46:"STYLE_SEPARATOR",48:"DOUBLECIRCLESTART",49:"DOUBLECIRCLEEND",50:"PS",51:"PE",52:"(-",53:"-)",54:"STADIUMSTART",55:"STADIUMEND",56:"SUBROUTINESTART",57:"SUBROUTINEEND",58:"VERTEX_WITH_PROPS_START",59:"NODE_STRING[field]",60:"COLON",61:"NODE_STRING[value]",62:"PIPE",63:"CYLINDERSTART",64:"CYLINDEREND",65:"DIAMOND_START",66:"DIAMOND_STOP",67:"TAGEND",68:"TRAPSTART",69:"TRAPEND",70:"INVTRAPSTART",71:"INVTRAPEND",74:"TESTSTR",75:"START_LINK",77:"LINK",78:"LINK_ID",80:"STR",81:"MD_STR",84:"STYLE",85:"LINKSTYLE",86:"CLASSDEF",87:"CLASS",88:"CLICK",89:"DOWN",90:"UP",93:"idString[vertex]",94:"idString[class]",95:"CALLBACKNAME",96:"CALLBACKARGS",97:"HREF",98:"LINK_TARGET",99:"STR[link]",100:"STR[tooltip]",102:"DEFAULT",104:"INTERPOLATE",105:"NUM",106:"COMMA",109:"NODE_STRING",110:"UNIT",111:"BRKT",112:"PCT",114:"MINUS",115:"MULT",116:"UNICODE_TEXT",117:"TEXT",118:"TAGSTART",119:"EDGE_TEXT",121:"direction_tb",122:"direction_bt",123:"direction_rl",124:"direction_lr",125:"direction_td"},+productions_: [0,[3,2],[5,0],[5,2],[6,1],[6,1],[6,1],[6,1],[6,1],[4,2],[4,2],[4,2],[4,3],[16,2],[16,1],[17,1],[17,1],[17,1],[15,1],[15,1],[15,2],[19,2],[19,2],[19,1],[19,1],[18,2],[18,1],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,9],[7,6],[7,4],[7,1],[7,2],[7,2],[7,1],[21,1],[21,1],[21,1],[39,2],[39,1],[20,4],[20,3],[20,4],[20,2],[20,2],[20,1],[42,1],[42,6],[42,5],[43,1],[43,3],[45,4],[45,4],[45,6],[45,4],[45,4],[45,4],[45,8],[45,4],[45,4],[45,4],[45,6],[45,4],[45,4],[45,4],[45,4],[45,4],[45,1],[41,2],[41,3],[41,3],[41,1],[41,3],[41,4],[76,1],[76,2],[76,1],[76,1],[72,1],[72,2],[73,3],[30,1],[30,2],[30,1],[30,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[28,1],[28,2],[28,1],[28,1],[24,5],[25,5],[26,2],[26,4],[26,3],[26,5],[26,3],[26,5],[26,5],[26,7],[26,2],[26,4],[26,2],[26,4],[26,4],[26,6],[22,5],[23,5],[23,5],[23,9],[23,9],[23,7],[23,7],[103,1],[103,3],[92,1],[92,3],[107,1],[107,2],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[82,1],[82,1],[82,1],[82,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[79,1],[79,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[47,1],[47,2],[101,1],[101,2],[33,1],[33,1],[33,1],[33,1],[33,1]],+performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) {+/* this == yyval */++var $0 = $$.length - 1;+switch (yystate) {+case 2:+ this.$ = [];+break;+case 3:++ if(!Array.isArray($$[$0]) || $$[$0].length > 0){+ $$[$0-1].push($$[$0]);+ }+ this.$=$$[$0-1];+break;+case 4: case 183:+this.$=$$[$0];+break;+case 11:+ yy.setDirection('TB');this.$ = 'TB';+break;+case 12:+ yy.setDirection($$[$0-1]);this.$ = $$[$0-1];+break;+case 27:+ this.$=$$[$0-1].nodes+break;+case 28: case 29: case 30: case 31: case 32:+this.$=[];+break;+case 33:+this.$=yy.addSubGraph($$[$0-6],$$[$0-1],$$[$0-4]);+break;+case 34:+this.$=yy.addSubGraph($$[$0-3],$$[$0-1],$$[$0-3]);+break;+case 35:+this.$=yy.addSubGraph(undefined,$$[$0-1],undefined);+break;+case 37:+ this.$=$$[$0].trim();yy.setAccTitle(this.$);+break;+case 38: case 39:+ this.$=$$[$0].trim();yy.setAccDescription(this.$);+break;+case 43:+ this.$ = $$[$0-1] + $$[$0];+break;+case 44:+ this.$ = $$[$0];+break;+case 45:+ /* console.warn('vs shapeData',$$[$0-3].stmt,$$[$0-1], $$[$0]);*/ yy.addVertex($$[$0-1][$$[$0-1].length-1],undefined,undefined,undefined, undefined,undefined, undefined,$$[$0]); yy.addLink($$[$0-3].stmt,$$[$0-1],$$[$0-2]); this.$ = { stmt: $$[$0-1], nodes: $$[$0-1].concat($$[$0-3].nodes) }+break;+case 46:+ /*console.warn('vs',$$[$0-2].stmt,$$[$0]);*/ yy.addLink($$[$0-2].stmt,$$[$0],$$[$0-1]); this.$ = { stmt: $$[$0], nodes: $$[$0].concat($$[$0-2].nodes) }+break;+case 47:+ /* console.warn('vs',$$[$0-3].stmt,$$[$0-1]); */ yy.addLink($$[$0-3].stmt,$$[$0-1],$$[$0-2]); this.$ = { stmt: $$[$0-1], nodes: $$[$0-1].concat($$[$0-3].nodes) }+break;+case 48:+ /*console.warn('vertexStatement: node spaceList', $$[$0-1]);*/ this.$ = {stmt: $$[$0-1], nodes:$$[$0-1] }+break;+case 49:++ /*console.warn('vertexStatement: node shapeData', $$[$0-1][0], $$[$0]);*/+ yy.addVertex($$[$0-1][$$[$0-1].length-1],undefined,undefined,undefined, undefined,undefined, undefined,$$[$0]);+ this.$ = {stmt: $$[$0-1], nodes:$$[$0-1], shapeData: $$[$0]}++break;+case 50:+ /* console.warn('vertexStatement: single node', $$[$0]); */ this.$ = {stmt: $$[$0], nodes:$$[$0] }+break;+case 51:+ /*console.warn('nod', $$[$0]);*/ this.$ = [$$[$0]];+break;+case 52:+ yy.addVertex($$[$0-5][$$[$0-5].length-1],undefined,undefined,undefined, undefined,undefined, undefined,$$[$0-4]); this.$ = $$[$0-5].concat($$[$0]); /*console.warn('pip2', $$[$0-5][0], $$[$0], this.$);*/+break;+case 53:+ this.$ = $$[$0-4].concat($$[$0]); /*console.warn('pip', $$[$0-4][0], $$[$0], this.$);*/+break;+case 54:+ /* console.warn('nodc', $$[$0]);*/ this.$ = $$[$0];+break;+case 55:+this.$ = $$[$0-2];yy.setClass($$[$0-2],$$[$0])+break;+case 56:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'square');+break;+case 57:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'doublecircle');+break;+case 58:+this.$ = $$[$0-5];yy.addVertex($$[$0-5],$$[$0-2],'circle');+break;+case 59:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'ellipse');+break;+case 60:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'stadium');+break;+case 61:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'subroutine');+break;+case 62:+this.$ = $$[$0-7];yy.addVertex($$[$0-7],$$[$0-1],'rect',undefined,undefined,undefined, Object.fromEntries([[$$[$0-5], $$[$0-3]]]));+break;+case 63:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'cylinder');+break;+case 64:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'round');+break;+case 65:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'diamond');+break;+case 66:+this.$ = $$[$0-5];yy.addVertex($$[$0-5],$$[$0-2],'hexagon');+break;+case 67:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'odd');+break;+case 68:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'trapezoid');+break;+case 69:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'inv_trapezoid');+break;+case 70:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'lean_right');+break;+case 71:+this.$ = $$[$0-3];yy.addVertex($$[$0-3],$$[$0-1],'lean_left');+break;+case 72:+ /*console.warn('h: ', $$[$0]);*/this.$ = $$[$0];yy.addVertex($$[$0]);+break;+case 73:+$$[$0-1].text = $$[$0];this.$ = $$[$0-1];+break;+case 74: case 75:+$$[$0-2].text = $$[$0-1];this.$ = $$[$0-2];+break;+case 76:+this.$ = $$[$0];+break;+case 77:+var inf = yy.destructLink($$[$0], $$[$0-2]); this.$ = {"type":inf.type,"stroke":inf.stroke,"length":inf.length,"text":$$[$0-1]};+break;+case 78:+var inf = yy.destructLink($$[$0], $$[$0-2]); this.$ = {"type":inf.type,"stroke":inf.stroke,"length":inf.length,"text":$$[$0-1], "id": $$[$0-3]};+break;+case 79:+this.$={text:$$[$0], type:'text'};+break;+case 80:+this.$={text:$$[$0-1].text+''+$$[$0], type:$$[$0-1].type};+break;+case 81:+this.$={text: $$[$0], type: 'string'};+break;+case 82:+this.$={text:$$[$0], type:'markdown'};+break;+case 83:+var inf = yy.destructLink($$[$0]);this.$ = {"type":inf.type,"stroke":inf.stroke,"length":inf.length};+break;+case 84:+var inf = yy.destructLink($$[$0]);this.$ = {"type":inf.type,"stroke":inf.stroke,"length":inf.length, "id": $$[$0-1]};+break;+case 85:+this.$ = $$[$0-1];+break;+case 86:+ this.$={text:$$[$0], type: 'text'};+break;+case 87:+ this.$={text:$$[$0-1].text+''+$$[$0], type: $$[$0-1].type};+break;+case 88:+ this.$ = {text: $$[$0], type: 'string'};+break;+case 89: case 104:+ this.$={text: $$[$0], type: 'markdown'};+break;+case 101:+this.$={text:$$[$0], type: 'text'};+break;+case 102:+this.$={text:$$[$0-1].text+''+$$[$0], type: $$[$0-1].type};+break;+case 103:+ this.$={text: $$[$0], type: 'text'};+break;+case 105:+this.$ = $$[$0-4];yy.addClass($$[$0-2],$$[$0]);+break;+case 106:+this.$ = $$[$0-4];yy.setClass($$[$0-2], $$[$0]);+break;+case 107: case 115:+this.$ = $$[$0-1];yy.setClickEvent($$[$0-1], $$[$0]);+break;+case 108: case 116:+this.$ = $$[$0-3];yy.setClickEvent($$[$0-3], $$[$0-2]);yy.setTooltip($$[$0-3], $$[$0]);+break;+case 109:+this.$ = $$[$0-2];yy.setClickEvent($$[$0-2], $$[$0-1], $$[$0]);+break;+case 110:+this.$ = $$[$0-4];yy.setClickEvent($$[$0-4], $$[$0-3], $$[$0-2]);yy.setTooltip($$[$0-4], $$[$0]);+break;+case 111:+this.$ = $$[$0-2];yy.setLink($$[$0-2], $$[$0]);+break;+case 112:+this.$ = $$[$0-4];yy.setLink($$[$0-4], $$[$0-2]);yy.setTooltip($$[$0-4], $$[$0]);+break;+case 113:+this.$ = $$[$0-4];yy.setLink($$[$0-4], $$[$0-2], $$[$0]);+break;+case 114:+this.$ = $$[$0-6];yy.setLink($$[$0-6], $$[$0-4], $$[$0]);yy.setTooltip($$[$0-6], $$[$0-2]);+break;+case 117:+this.$ = $$[$0-1];yy.setLink($$[$0-1], $$[$0]);+break;+case 118:+this.$ = $$[$0-3];yy.setLink($$[$0-3], $$[$0-2]);yy.setTooltip($$[$0-3], $$[$0]);+break;+case 119:+this.$ = $$[$0-3];yy.setLink($$[$0-3], $$[$0-2], $$[$0]);+break;+case 120:+this.$ = $$[$0-5];yy.setLink($$[$0-5], $$[$0-4], $$[$0]);yy.setTooltip($$[$0-5], $$[$0-2]);+break;+case 121:+this.$ = $$[$0-4];yy.addVertex($$[$0-2],undefined,undefined,$$[$0]);+break;+case 122:+this.$ = $$[$0-4];yy.updateLink([$$[$0-2]],$$[$0]);+break;+case 123:+this.$ = $$[$0-4];yy.updateLink($$[$0-2],$$[$0]);+break;+case 124:+this.$ = $$[$0-8];yy.updateLinkInterpolate([$$[$0-6]],$$[$0-2]);yy.updateLink([$$[$0-6]],$$[$0]);+break;+case 125:+this.$ = $$[$0-8];yy.updateLinkInterpolate($$[$0-6],$$[$0-2]);yy.updateLink($$[$0-6],$$[$0]);+break;+case 126:+this.$ = $$[$0-6];yy.updateLinkInterpolate([$$[$0-4]],$$[$0]);+break;+case 127:+this.$ = $$[$0-6];yy.updateLinkInterpolate($$[$0-4],$$[$0]);+break;+case 128: case 130:+this.$ = [$$[$0]]+break;+case 129: case 131:+$$[$0-2].push($$[$0]);this.$ = $$[$0-2];+break;+case 133:+this.$ = $$[$0-1] + $$[$0];+break;+case 181:+this.$=$$[$0]+break;+case 182:+this.$=$$[$0-1]+''+$$[$0]+break;+case 184:+this.$=$$[$0-1]+''+$$[$0];+break;+case 185:+ this.$={stmt:'dir', value:'TB'};+break;+case 186:+ this.$={stmt:'dir', value:'BT'};+break;+case 187:+ this.$={stmt:'dir', value:'RL'};+break;+case 188:+ this.$={stmt:'dir', value:'LR'};+break;+case 189:+ this.$={stmt:'dir', value:'TD'};+break;+}+},+table: [{3:1,4:2,9:$V0,10:$V1,12:$V2},{1:[3]},o($V3,$V4,{5:6}),{4:7,9:$V0,10:$V1,12:$V2},{4:8,9:$V0,10:$V1,12:$V2},{13:[1,9],14:[1,10]},{1:[2,1],6:11,7:12,8:$V5,9:$V6,10:$V7,11:$V8,20:17,22:18,23:19,24:20,25:21,26:22,27:$V9,33:24,34:$Va,36:$Vb,38:$Vc,42:28,43:39,44:$Vd,45:40,47:41,60:$Ve,84:$Vf,85:$Vg,86:$Vh,87:$Vi,88:$Vj,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs,121:$Vt,122:$Vu,123:$Vv,124:$Vw,125:$Vx},o($V3,[2,9]),o($V3,[2,10]),o($V3,[2,11]),{8:[1,55],9:[1,56],10:$Vy,15:54,18:57},o($Vz,[2,3]),o($Vz,[2,4]),o($Vz,[2,5]),o($Vz,[2,6]),o($Vz,[2,7]),o($Vz,[2,8]),{8:$VA,9:$VB,11:$VC,21:59,41:60,72:64,75:[1,65],77:[1,67],78:[1,66]},{8:$VA,9:$VB,11:$VC,21:68},{8:$VA,9:$VB,11:$VC,21:69},{8:$VA,9:$VB,11:$VC,21:70},{8:$VA,9:$VB,11:$VC,21:71},{8:$VA,9:$VB,11:$VC,21:72},{8:$VA,9:$VB,10:[1,73],11:$VC,21:74},o($Vz,[2,36]),{35:[1,75]},{37:[1,76]},o($Vz,[2,39]),o($VD,[2,50],{18:77,39:78,10:$Vy,40:$VE}),{10:[1,80]},{10:[1,81]},{10:[1,82]},{10:[1,83]},{14:$VF,44:$VG,60:$VH,80:[1,87],89:$VI,95:[1,84],97:[1,85],101:86,105:$VJ,106:$VK,109:$VL,111:$VM,114:$VN,115:$VO,116:$VP,120:88},o($Vz,[2,185]),o($Vz,[2,186]),o($Vz,[2,187]),o($Vz,[2,188]),o($Vz,[2,189]),o($VQ,[2,51]),o($VQ,[2,54],{46:[1,100]}),o($VR,[2,72],{113:113,29:[1,101],44:$Vd,48:[1,102],50:[1,103],52:[1,104],54:[1,105],56:[1,106],58:[1,107],60:$Ve,63:[1,108],65:[1,109],67:[1,110],68:[1,111],70:[1,112],89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,114:$Vq,115:$Vr,116:$Vs}),o($VS,[2,181]),o($VS,[2,142]),o($VS,[2,143]),o($VS,[2,144]),o($VS,[2,145]),o($VS,[2,146]),o($VS,[2,147]),o($VS,[2,148]),o($VS,[2,149]),o($VS,[2,150]),o($VS,[2,151]),o($VS,[2,152]),o($V3,[2,12]),o($V3,[2,18]),o($V3,[2,19]),{9:[1,114]},o($VT,[2,26],{18:115,10:$Vy}),o($Vz,[2,27]),{42:116,43:39,44:$Vd,45:40,47:41,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs},o($Vz,[2,40]),o($Vz,[2,41]),o($Vz,[2,42]),o($VU,[2,76],{73:117,62:[1,119],74:[1,118]}),{76:120,79:121,80:$VV,81:$VW,116:$VX,119:$VY},{75:[1,126],77:[1,127]},o($VZ,[2,83]),o($Vz,[2,28]),o($Vz,[2,29]),o($Vz,[2,30]),o($Vz,[2,31]),o($Vz,[2,32]),{10:$V_,12:$V$,14:$V01,27:$V11,28:128,32:$V21,44:$V31,60:$V41,75:$V51,80:[1,130],81:[1,131],83:141,84:$V61,85:$V71,86:$V81,87:$V91,88:$Va1,89:$Vb1,90:$Vc1,91:129,105:$Vd1,109:$Ve1,111:$Vf1,114:$Vg1,115:$Vh1,116:$Vi1},o($Vj1,$V4,{5:154}),o($Vz,[2,37]),o($Vz,[2,38]),o($VD,[2,48],{44:$Vk1}),o($VD,[2,49],{18:156,10:$Vy,40:$Vl1}),o($VQ,[2,44]),{44:$Vd,47:158,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs},{102:[1,159],103:160,105:[1,161]},{44:$Vd,47:162,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs},{44:$Vd,47:163,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs},o($Vm1,[2,107],{10:[1,164],96:[1,165]}),{80:[1,166]},o($Vm1,[2,115],{120:168,10:[1,167],14:$VF,44:$VG,60:$VH,89:$VI,105:$VJ,106:$VK,109:$VL,111:$VM,114:$VN,115:$VO,116:$VP}),o($Vm1,[2,117],{10:[1,169]}),o($Vn1,[2,183]),o($Vn1,[2,170]),o($Vn1,[2,171]),o($Vn1,[2,172]),o($Vn1,[2,173]),o($Vn1,[2,174]),o($Vn1,[2,175]),o($Vn1,[2,176]),o($Vn1,[2,177]),o($Vn1,[2,178]),o($Vn1,[2,179]),o($Vn1,[2,180]),{44:$Vd,47:170,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs},{30:171,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{30:179,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{30:181,50:[1,180],67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{30:182,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{30:183,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{30:184,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{109:[1,185]},{30:186,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{30:187,65:[1,188],67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{30:189,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{30:190,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{30:191,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},o($VS,[2,182]),o($V3,[2,20]),o($VT,[2,25]),o($VD,[2,46],{39:192,18:193,10:$Vy,40:$VE}),o($VU,[2,73],{10:[1,194]}),{10:[1,195]},{30:196,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{77:[1,197],79:198,116:$VX,119:$VY},o($Vu1,[2,79]),o($Vu1,[2,81]),o($Vu1,[2,82]),o($Vu1,[2,168]),o($Vu1,[2,169]),{76:199,79:121,80:$VV,81:$VW,116:$VX,119:$VY},o($VZ,[2,84]),{8:$VA,9:$VB,10:$V_,11:$VC,12:$V$,14:$V01,21:201,27:$V11,29:[1,200],32:$V21,44:$V31,60:$V41,75:$V51,83:141,84:$V61,85:$V71,86:$V81,87:$V91,88:$Va1,89:$Vb1,90:$Vc1,91:202,105:$Vd1,109:$Ve1,111:$Vf1,114:$Vg1,115:$Vh1,116:$Vi1},o($Vv1,[2,101]),o($Vv1,[2,103]),o($Vv1,[2,104]),o($Vv1,[2,157]),o($Vv1,[2,158]),o($Vv1,[2,159]),o($Vv1,[2,160]),o($Vv1,[2,161]),o($Vv1,[2,162]),o($Vv1,[2,163]),o($Vv1,[2,164]),o($Vv1,[2,165]),o($Vv1,[2,166]),o($Vv1,[2,167]),o($Vv1,[2,90]),o($Vv1,[2,91]),o($Vv1,[2,92]),o($Vv1,[2,93]),o($Vv1,[2,94]),o($Vv1,[2,95]),o($Vv1,[2,96]),o($Vv1,[2,97]),o($Vv1,[2,98]),o($Vv1,[2,99]),o($Vv1,[2,100]),{6:11,7:12,8:$V5,9:$V6,10:$V7,11:$V8,20:17,22:18,23:19,24:20,25:21,26:22,27:$V9,32:[1,203],33:24,34:$Va,36:$Vb,38:$Vc,42:28,43:39,44:$Vd,45:40,47:41,60:$Ve,84:$Vf,85:$Vg,86:$Vh,87:$Vi,88:$Vj,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs,121:$Vt,122:$Vu,123:$Vv,124:$Vw,125:$Vx},{10:$Vy,18:204},{44:[1,205]},o($VQ,[2,43]),{10:[1,206],44:$Vd,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:113,114:$Vq,115:$Vr,116:$Vs},{10:[1,207]},{10:[1,208],106:[1,209]},o($Vw1,[2,128]),{10:[1,210],44:$Vd,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:113,114:$Vq,115:$Vr,116:$Vs},{10:[1,211],44:$Vd,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:113,114:$Vq,115:$Vr,116:$Vs},{80:[1,212]},o($Vm1,[2,109],{10:[1,213]}),o($Vm1,[2,111],{10:[1,214]}),{80:[1,215]},o($Vn1,[2,184]),{80:[1,216],98:[1,217]},o($VQ,[2,55],{113:113,44:$Vd,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,114:$Vq,115:$Vr,116:$Vs}),{31:[1,218],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},o($Vx1,[2,86]),o($Vx1,[2,88]),o($Vx1,[2,89]),o($Vx1,[2,153]),o($Vx1,[2,154]),o($Vx1,[2,155]),o($Vx1,[2,156]),{49:[1,220],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},{30:221,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{51:[1,222],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},{53:[1,223],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},{55:[1,224],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},{57:[1,225],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},{60:[1,226]},{64:[1,227],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},{66:[1,228],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},{30:229,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},{31:[1,230],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},{67:$Vo1,69:[1,231],71:[1,232],82:219,116:$Vr1,117:$Vs1,118:$Vt1},{67:$Vo1,69:[1,234],71:[1,233],82:219,116:$Vr1,117:$Vs1,118:$Vt1},o($VD,[2,45],{18:156,10:$Vy,40:$Vl1}),o($VD,[2,47],{44:$Vk1}),o($VU,[2,75]),o($VU,[2,74]),{62:[1,235],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},o($VU,[2,77]),o($Vu1,[2,80]),{77:[1,236],79:198,116:$VX,119:$VY},{30:237,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},o($Vj1,$V4,{5:238}),o($Vv1,[2,102]),o($Vz,[2,35]),{43:239,44:$Vd,45:40,47:41,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs},{10:$Vy,18:240},{10:$Vy1,60:$Vz1,84:$VA1,92:241,105:$VB1,107:242,108:243,109:$VC1,110:$VD1,111:$VE1,112:$VF1},{10:$Vy1,60:$Vz1,84:$VA1,92:252,104:[1,253],105:$VB1,107:242,108:243,109:$VC1,110:$VD1,111:$VE1,112:$VF1},{10:$Vy1,60:$Vz1,84:$VA1,92:254,104:[1,255],105:$VB1,107:242,108:243,109:$VC1,110:$VD1,111:$VE1,112:$VF1},{105:[1,256]},{10:$Vy1,60:$Vz1,84:$VA1,92:257,105:$VB1,107:242,108:243,109:$VC1,110:$VD1,111:$VE1,112:$VF1},{44:$Vd,47:258,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs},o($Vm1,[2,108]),{80:[1,259]},{80:[1,260],98:[1,261]},o($Vm1,[2,116]),o($Vm1,[2,118],{10:[1,262]}),o($Vm1,[2,119]),o($VR,[2,56]),o($Vx1,[2,87]),o($VR,[2,57]),{51:[1,263],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},o($VR,[2,64]),o($VR,[2,59]),o($VR,[2,60]),o($VR,[2,61]),{109:[1,264]},o($VR,[2,63]),o($VR,[2,65]),{66:[1,265],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},o($VR,[2,67]),o($VR,[2,68]),o($VR,[2,70]),o($VR,[2,69]),o($VR,[2,71]),o([10,44,60,89,102,105,106,109,111,114,115,116],[2,85]),o($VU,[2,78]),{31:[1,266],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},{6:11,7:12,8:$V5,9:$V6,10:$V7,11:$V8,20:17,22:18,23:19,24:20,25:21,26:22,27:$V9,32:[1,267],33:24,34:$Va,36:$Vb,38:$Vc,42:28,43:39,44:$Vd,45:40,47:41,60:$Ve,84:$Vf,85:$Vg,86:$Vh,87:$Vi,88:$Vj,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs,121:$Vt,122:$Vu,123:$Vv,124:$Vw,125:$Vx},o($VQ,[2,53]),{43:268,44:$Vd,45:40,47:41,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs},o($Vm1,[2,121],{106:$VG1}),o($VH1,[2,130],{108:270,10:$Vy1,60:$Vz1,84:$VA1,105:$VB1,109:$VC1,110:$VD1,111:$VE1,112:$VF1}),o($VI1,[2,132]),o($VI1,[2,134]),o($VI1,[2,135]),o($VI1,[2,136]),o($VI1,[2,137]),o($VI1,[2,138]),o($VI1,[2,139]),o($VI1,[2,140]),o($VI1,[2,141]),o($Vm1,[2,122],{106:$VG1}),{10:[1,271]},o($Vm1,[2,123],{106:$VG1}),{10:[1,272]},o($Vw1,[2,129]),o($Vm1,[2,105],{106:$VG1}),o($Vm1,[2,106],{113:113,44:$Vd,60:$Ve,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,114:$Vq,115:$Vr,116:$Vs}),o($Vm1,[2,110]),o($Vm1,[2,112],{10:[1,273]}),o($Vm1,[2,113]),{98:[1,274]},{51:[1,275]},{62:[1,276]},{66:[1,277]},{8:$VA,9:$VB,11:$VC,21:278},o($Vz,[2,34]),o($VQ,[2,52]),{10:$Vy1,60:$Vz1,84:$VA1,105:$VB1,107:279,108:243,109:$VC1,110:$VD1,111:$VE1,112:$VF1},o($VI1,[2,133]),{14:$VF,44:$VG,60:$VH,89:$VI,101:280,105:$VJ,106:$VK,109:$VL,111:$VM,114:$VN,115:$VO,116:$VP,120:88},{14:$VF,44:$VG,60:$VH,89:$VI,101:281,105:$VJ,106:$VK,109:$VL,111:$VM,114:$VN,115:$VO,116:$VP,120:88},{98:[1,282]},o($Vm1,[2,120]),o($VR,[2,58]),{30:283,67:$Vo1,80:$Vp1,81:$Vq1,82:172,116:$Vr1,117:$Vs1,118:$Vt1},o($VR,[2,66]),o($Vj1,$V4,{5:284}),o($VH1,[2,131],{108:270,10:$Vy1,60:$Vz1,84:$VA1,105:$VB1,109:$VC1,110:$VD1,111:$VE1,112:$VF1}),o($Vm1,[2,126],{120:168,10:[1,285],14:$VF,44:$VG,60:$VH,89:$VI,105:$VJ,106:$VK,109:$VL,111:$VM,114:$VN,115:$VO,116:$VP}),o($Vm1,[2,127],{120:168,10:[1,286],14:$VF,44:$VG,60:$VH,89:$VI,105:$VJ,106:$VK,109:$VL,111:$VM,114:$VN,115:$VO,116:$VP}),o($Vm1,[2,114]),{31:[1,287],67:$Vo1,82:219,116:$Vr1,117:$Vs1,118:$Vt1},{6:11,7:12,8:$V5,9:$V6,10:$V7,11:$V8,20:17,22:18,23:19,24:20,25:21,26:22,27:$V9,32:[1,288],33:24,34:$Va,36:$Vb,38:$Vc,42:28,43:39,44:$Vd,45:40,47:41,60:$Ve,84:$Vf,85:$Vg,86:$Vh,87:$Vi,88:$Vj,89:$Vk,102:$Vl,105:$Vm,106:$Vn,109:$Vo,111:$Vp,113:42,114:$Vq,115:$Vr,116:$Vs,121:$Vt,122:$Vu,123:$Vv,124:$Vw,125:$Vx},{10:$Vy1,60:$Vz1,84:$VA1,92:289,105:$VB1,107:242,108:243,109:$VC1,110:$VD1,111:$VE1,112:$VF1},{10:$Vy1,60:$Vz1,84:$VA1,92:290,105:$VB1,107:242,108:243,109:$VC1,110:$VD1,111:$VE1,112:$VF1},o($VR,[2,62]),o($Vz,[2,33]),o($Vm1,[2,124],{106:$VG1}),o($Vm1,[2,125],{106:$VG1})],+defaultActions: {},+parseError: function parseError(str, hash) {+ if (hash.recoverable)+ this.trace(str);+ else {+ var error = Error(str);+ error.hash = hash;+ throw error;+ }+ },+parse: function parse(input) {+ var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1, args = lstack.slice.call(arguments, 1), lexer = Object.create(this.lexer), sharedState = { yy: {} };+ for (var k in this.yy)+ if (Object.prototype.hasOwnProperty.call(this.yy, k))+ sharedState.yy[k] = this.yy[k];+ lexer.setInput(input, sharedState.yy);+ sharedState.yy.lexer = lexer;+ sharedState.yy.parser = this;+ if (typeof lexer.yylloc > "u")+ lexer.yylloc = {};+ var yyloc = lexer.yylloc;+ lstack.push(yyloc);+ var ranges = lexer.options && lexer.options.ranges;+ if (typeof sharedState.yy.parseError === "function")+ this.parseError = sharedState.yy.parseError;+ else+ this.parseError = Object.getPrototypeOf(this).parseError;+ function popStack(n) {+ stack.length = stack.length - 2 * n;+ vstack.length = vstack.length - n;+ lstack.length = lstack.length - n;+ }+ _token_stack:+ var lex = function() {+ var token = lexer.lex() || EOF;+ if (typeof token !== "number")+ token = self.symbols_[token] || token;+ return token;+ };+ var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;+ while (!0) {+ state = stack[stack.length - 1];+ if (this.defaultActions[state])+ action = this.defaultActions[state];+ else {+ if (symbol === null || typeof symbol > "u")+ symbol = lex();+ action = table[state] && table[state][symbol];+ }+ _handle_error:+ if (typeof action > "u" || !action.length || !action[0]) {+ let locateNearestErrorRecoveryRule = function(state) {+ var stack_probe = stack.length - 1, depth = 0;+ for (;; ) {+ if (TERROR.toString() in table[state])+ return depth;+ if (state === 0 || stack_probe < 2)+ return !1;+ stack_probe -= 2;+ state = stack[stack_probe];+ ++depth;+ }+ };+ var error_rule_depth, errStr = "";+ if (!recovering) {+ error_rule_depth = locateNearestErrorRecoveryRule(state);+ expected = [];+ for (p in table[state])+ if (this.terminals_[p] && p > TERROR)+ expected.push("'" + this.terminals_[p] + "'");+ if (lexer.showPosition)+ errStr = "Parse error on line " + (yylineno + 1) + `:+` + lexer.showPosition() + `+Expecting ` + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";+ else+ errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == EOF ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");+ this.parseError(errStr, {+ text: lexer.match,+ token: this.terminals_[symbol] || symbol,+ line: lexer.yylineno,+ loc: yyloc,+ expected,+ recoverable: error_rule_depth !== !1+ });+ } else if (preErrorSymbol !== EOF)+ error_rule_depth = locateNearestErrorRecoveryRule(state);+ if (recovering == 3) {+ if (symbol === EOF || preErrorSymbol === EOF)+ throw Error(errStr || "Parsing halted while starting to recover from another error.");+ yyleng = lexer.yyleng;+ yytext = lexer.yytext;+ yylineno = lexer.yylineno;+ yyloc = lexer.yylloc;+ symbol = lex();+ }+ if (error_rule_depth === !1)+ throw Error(errStr || "Parsing halted. No suitable error recovery rule available.");+ popStack(error_rule_depth);+ preErrorSymbol = symbol == TERROR ? null : symbol;+ symbol = TERROR;+ state = stack[stack.length - 1];+ action = table[state] && table[state][TERROR];+ recovering = 3;+ }+ if (action[0] instanceof Array && action.length > 1)+ throw Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);+ switch (action[0]) {+ case 1:+ stack.push(symbol);+ vstack.push(lexer.yytext);+ lstack.push(lexer.yylloc);+ stack.push(action[1]);+ symbol = null;+ if (!preErrorSymbol) {+ yyleng = lexer.yyleng;+ yytext = lexer.yytext;+ yylineno = lexer.yylineno;+ yyloc = lexer.yylloc;+ if (recovering > 0)+ recovering--;+ } else {+ symbol = preErrorSymbol;+ preErrorSymbol = null;+ }+ break;+ case 2:+ len = this.productions_[action[1]][1];+ yyval.$ = vstack[vstack.length - len];+ yyval._$ = {+ first_line: lstack[lstack.length - (len || 1)].first_line,+ last_line: lstack[lstack.length - 1].last_line,+ first_column: lstack[lstack.length - (len || 1)].first_column,+ last_column: lstack[lstack.length - 1].last_column+ };+ if (ranges)+ yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];+ r = this.performAction.apply(yyval, [yytext, yyleng, yylineno, sharedState.yy, action[1], vstack, lstack].concat(args));+ if (typeof r < "u")+ return r;+ if (len) {+ stack = stack.slice(0, -1 * len * 2);+ vstack = vstack.slice(0, -1 * len);+ lstack = lstack.slice(0, -1 * len);+ }+ stack.push(this.productions_[action[1]][0]);+ vstack.push(yyval.$);+ lstack.push(yyval._$);+ newState = table[stack[stack.length - 2]][stack[stack.length - 1]];+ stack.push(newState);+ break;+ case 3:+ return !0;+ }+ }+ return !0;+ }};++/* generated by jison-lex 0.3.4 */+var lexer = (function(){+var lexer = ({++EOF:1,++parseError:function parseError(str, hash) {+ if (this.yy.parser)+ this.yy.parser.parseError(str, hash);+ else+ throw Error(str);+ },++// resets the lexer, sets new input+setInput:function(input, yy) {+ this.yy = yy || this.yy || {};+ this._input = input;+ this._more = this._backtrack = this.done = !1;+ this.yylineno = this.yyleng = 0;+ this.yytext = this.matched = this.match = "";+ this.conditionStack = ["INITIAL"];+ this.yylloc = {+ first_line: 1,+ first_column: 0,+ last_line: 1,+ last_column: 0+ };+ if (this.options.ranges)+ this.yylloc.range = [0, 0];+ this.offset = 0;+ return this;+ },++// consumes and returns one char from the input+input:function() {+ var ch = this._input[0];+ this.yytext += ch;+ this.yyleng++;+ this.offset++;+ this.match += ch;+ this.matched += ch;+ var lines = ch.match(/(?:\r\n?|\n).*/g);+ if (lines) {+ this.yylineno++;+ this.yylloc.last_line++;+ } else+ this.yylloc.last_column++;+ if (this.options.ranges)+ this.yylloc.range[1]++;+ this._input = this._input.slice(1);+ return ch;+ },++// unshifts one char (or a string) into the input+unput:function(ch) {+ var len = ch.length, lines = ch.split(/(?:\r\n?|\n)/g);+ this._input = ch + this._input;+ this.yytext = this.yytext.substr(0, this.yytext.length - len);+ this.offset -= len;+ var oldLines = this.match.split(/(?:\r\n?|\n)/g);+ this.match = this.match.substr(0, this.match.length - 1);+ this.matched = this.matched.substr(0, this.matched.length - 1);+ if (lines.length - 1)+ this.yylineno -= lines.length - 1;+ var r = this.yylloc.range;+ this.yylloc = {+ first_line: this.yylloc.first_line,+ last_line: this.yylineno + 1,+ first_column: this.yylloc.first_column,+ last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len+ };+ if (this.options.ranges)+ this.yylloc.range = [r[0], r[0] + this.yyleng - len];+ this.yyleng = this.yytext.length;+ return this;+ },++// When called from action, caches matched text and appends it on next action+more:function() {+ this._more = !0;+ return this;+ },++// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.+reject:function() {+ if (this.options.backtrack_lexer)+ this._backtrack = !0;+ else+ return this.parseError("Lexical error on line " + (this.yylineno + 1) + `. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).+` + this.showPosition(), {+ text: "",+ token: null,+ line: this.yylineno+ });+ return this;+ },++// retain first n characters of the match+less:function(n) {+ this.unput(this.match.slice(n));+ },++// displays already matched input, i.e. for error messages+pastInput:function() {+ var past = this.matched.substr(0, this.matched.length - this.match.length);+ return (past.length > 20 ? "..." : "") + past.substr(-20).replace(/\n/g, "");+ },++// displays upcoming input, i.e. for error messages+upcomingInput:function() {+ var next = this.match;+ if (next.length < 20)+ next += this._input.substr(0, 20 - next.length);+ return (next.substr(0, 20) + (next.length > 20 ? "..." : "")).replace(/\n/g, "");+ },++// displays the character position where the lexing error occurred, i.e. for error messages+showPosition:function() {+ var pre = this.pastInput(), c = Array(pre.length + 1).join("-");+ return pre + this.upcomingInput() + `+` + c + "^";+ },++// test the lexed token: return FALSE when not a match, otherwise return token+test_match:function(match, indexed_rule) {+ var token, lines, backup;+ if (this.options.backtrack_lexer) {+ backup = {+ yylineno: this.yylineno,+ yylloc: {+ first_line: this.yylloc.first_line,+ last_line: this.last_line,+ first_column: this.yylloc.first_column,+ last_column: this.yylloc.last_column+ },+ yytext: this.yytext,+ match: this.match,+ matches: this.matches,+ matched: this.matched,+ yyleng: this.yyleng,+ offset: this.offset,+ _more: this._more,+ _input: this._input,+ yy: this.yy,+ conditionStack: this.conditionStack.slice(0),+ done: this.done+ };+ if (this.options.ranges)+ backup.yylloc.range = this.yylloc.range.slice(0);+ }+ lines = match[0].match(/(?:\r\n?|\n).*/g);+ if (lines)+ this.yylineno += lines.length;+ this.yylloc = {+ first_line: this.yylloc.last_line,+ last_line: this.yylineno + 1,+ first_column: this.yylloc.last_column,+ last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length+ };+ this.yytext += match[0];+ this.match += match[0];+ this.matches = match;+ this.yyleng = this.yytext.length;+ if (this.options.ranges)+ this.yylloc.range = [this.offset, this.offset += this.yyleng];+ this._more = !1;+ this._backtrack = !1;+ this._input = this._input.slice(match[0].length);+ this.matched += match[0];+ token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);+ if (this.done && this._input)+ this.done = !1;+ if (token)+ return token;+ else if (this._backtrack) {+ for (var k in backup)+ this[k] = backup[k];+ return !1;+ }+ return !1;+ },++// return next match in input+next:function() {+ if (this.done)+ return this.EOF;+ if (!this._input)+ this.done = !0;+ var token, match, tempMatch, index;+ if (!this._more) {+ this.yytext = "";+ this.match = "";+ }+ var rules = this._currentRules();+ for (var i = 0;i < rules.length; i++) {+ tempMatch = this._input.match(this.rules[rules[i]]);+ if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {+ match = tempMatch;+ index = i;+ if (this.options.backtrack_lexer) {+ token = this.test_match(tempMatch, rules[i]);+ if (token !== !1)+ return token;+ else if (this._backtrack) {+ match = !1;+ continue;+ } else+ return !1;+ } else if (!this.options.flex)+ break;+ }+ }+ if (match) {+ token = this.test_match(match, rules[index]);+ if (token !== !1)+ return token;+ return !1;+ }+ if (this._input === "")+ return this.EOF;+ else+ return this.parseError("Lexical error on line " + (this.yylineno + 1) + `. Unrecognized text.+` + this.showPosition(), {+ text: "",+ token: null,+ line: this.yylineno+ });+ },++// return next match that has a token+lex:function lex() {+ var r = this.next();+ if (r)+ return r;+ else+ return this.lex();+ },++// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)+begin:function begin(condition) {+ this.conditionStack.push(condition);+ },++// pop the previously active lexer condition state off the condition stack+popState:function popState() {+ var n = this.conditionStack.length - 1;+ if (n > 0)+ return this.conditionStack.pop();+ else+ return this.conditionStack[0];+ },++// produce the lexer rule set which is active for the currently active lexer condition state+_currentRules:function _currentRules() {+ if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1])+ return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;+ else+ return this.conditions.INITIAL.rules;+ },++// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available+topState:function topState(n) {+ n = this.conditionStack.length - 1 - Math.abs(n || 0);+ if (n >= 0)+ return this.conditionStack[n];+ else+ return "INITIAL";+ },++// alias for begin(condition)+pushState:function pushState(condition) {+ this.begin(condition);+ },++// return the number of states currently on the stack+stateStackSize:function stateStackSize() {+ return this.conditionStack.length;+ },+options: {},+performAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {+var YYSTATE=YY_START;+switch($avoiding_name_collisions) {+case 0: this.begin("acc_title");return 34;+break;+case 1: this.popState(); return "acc_title_value";+break;+case 2: this.begin("acc_descr");return 36;+break;+case 3: this.popState(); return "acc_descr_value";+break;+case 4: this.begin("acc_descr_multiline");+break;+case 5: this.popState();+break;+case 6:return "acc_descr_multiline_value";+break;+case 7:+ // console.log('=> shapeData', yy_.yytext);+ this.pushState("shapeData"); yy_.yytext=""; return 40+break;+case 8:+ // console.log('=> shapeDataStr', yy_.yytext);+ this.pushState("shapeDataStr");+ return 40;++break;+case 9:+ // console.log('shapeData <==', yy_.yytext);+ this.popState(); return 40+break;+case 10:+ // console.log('shapeData', yy_.yytext);+ const re = /\n\s*/g;+ yy_.yytext = yy_.yytext.replace(re,"<br/>");+ return 40+break;+case 11:+ // console.log('shapeData', yy_.yytext);+ return 40;++break;+case 12:+ // console.log('<== root', yy_.yytext)+ this.popState();++break;+case 13:this.begin("callbackname");+break;+case 14:this.popState();+break;+case 15:this.popState(); this.begin("callbackargs");+break;+case 16:return 95;+break;+case 17:this.popState();+break;+case 18:return 96;+break;+case 19: return "MD_STR";+break;+case 20: this.popState();+break;+case 21: this.begin("md_string");+break;+case 22: return "STR";+break;+case 23:this.popState();+break;+case 24:this.pushState("string");+break;+case 25:return 84;+break;+case 26:return 102;+break;+case 27:return 85;+break;+case 28:return 104;+break;+case 29:return 86;+break;+case 30:return 87;+break;+case 31:return 97;+break;+case 32:this.begin("click");+break;+case 33:this.popState();+break;+case 34:return 88;+break;+case 35:if(yy.lex.firstGraph()){this.begin("dir");} return 12;+break;+case 36:if(yy.lex.firstGraph()){this.begin("dir");} return 12;+break;+case 37:if(yy.lex.firstGraph()){this.begin("dir");} return 12;+break;+case 38:if(yy.lex.firstGraph()){this.begin("dir");} return 12;+break;+case 39:return 27;+break;+case 40:return 32;+break;+case 41:return 98;+break;+case 42:return 98;+break;+case 43:return 98;+break;+case 44:return 98;+break;+case 45: this.popState(); return 13;+break;+case 46: this.popState(); return 14;+break;+case 47: this.popState(); return 14;+break;+case 48: this.popState(); return 14;+break;+case 49: this.popState(); return 14;+break;+case 50: this.popState(); return 14;+break;+case 51: this.popState(); return 14;+break;+case 52: this.popState(); return 14;+break;+case 53: this.popState(); return 14;+break;+case 54: this.popState(); return 14;+break;+case 55: this.popState(); return 14;+break;+case 56:return 121;+break;+case 57:return 122;+break;+case 58:return 123;+break;+case 59:return 124;+break;+case 60:return 125;+break;+case 61: return 78;+break;+case 62:return 105;+break;+case 63:return 111;+break;+case 64:return 46;+break;+case 65:return 60;+break;+case 66:return 44;+break;+case 67:return 8;+break;+case 68:return 106;+break;+case 69:return 115;+break;+case 70: this.popState(); return 77;+break;+case 71: this.pushState("edgeText"); return 75;+break;+case 72:return 119;+break;+case 73: this.popState(); return 77;+break;+case 74: this.pushState("thickEdgeText"); return 75;+break;+case 75:return 119;+break;+case 76: this.popState(); return 77;+break;+case 77: this.pushState("dottedEdgeText"); return 75;+break;+case 78:return 119;+break;+case 79:return 77;+break;+case 80: this.popState(); return 53;+break;+case 81:return "TEXT"+break;+case 82: this.pushState("ellipseText"); return 52;+break;+case 83: this.popState(); return 55;+break;+case 84: this.pushState("text"); return 54;+break;+case 85: this.popState(); return 57;+break;+case 86: this.pushState("text"); return 56;+break;+case 87: return 58;+break;+case 88: this.pushState("text"); return 67;+break;+case 89: this.popState(); return 64;+break;+case 90: this.pushState("text") ;return 63;+break;+case 91: this.popState(); return 49;+break;+case 92: this.pushState("text"); return 48;+break;+case 93: this.popState(); return 69;+break;+case 94: this.popState(); return 71;+break;+case 95:return 117;+break;+case 96: this.pushState("trapText"); return 68;+break;+case 97: this.pushState("trapText"); return 70;+break;+case 98:return 118;+break;+case 99:return 67;+break;+case 100:return 90;+break;+case 101:return 'SEP';+break;+case 102:return 89;+break;+case 103:return 115;+break;+case 104:return 111;+break;+case 105:return 44;+break;+case 106:+ return 109;++break;+case 107:return 114+break;+case 108:return 116;+break;+case 109: this.popState(); return 62;+break;+case 110: this.pushState("text"); return 62;+break;+case 111: this.popState(); return 51;+break;+case 112: this.pushState("text"); return 50;+break;+case 113: this.popState(); return 31;+break;+case 114: this.pushState("text"); return 29;+break;+case 115: this.popState(); return 66+break;+case 116: this.pushState("text"); return 65+break;+case 117:return "TEXT";+break;+case 118:return 'QUOTE';+break;+case 119:return 9;+break;+case 120:return 10;+break;+case 121:return 11;+break;+}+},+rules: [/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:@\{)/,/^(?:["])/,/^(?:["])/,/^(?:[^\"]+)/,/^(?:[^}^"]+)/,/^(?:\})/,/^(?:call[\s]+)/,/^(?:\([\s]*\))/,/^(?:\()/,/^(?:[^(]*)/,/^(?:\))/,/^(?:[^)]*)/,/^(?:[^`"]+)/,/^(?:[`]["])/,/^(?:["][`])/,/^(?:[^"]+)/,/^(?:["])/,/^(?:["])/,/^(?:style\b)/,/^(?:default\b)/,/^(?:linkStyle\b)/,/^(?:interpolate\b)/,/^(?:classDef\b)/,/^(?:class\b)/,/^(?:href[\s])/,/^(?:click[\s]+)/,/^(?:[\s\n])/,/^(?:[^\s\n]*)/,/^(?:flowchart-elk\b)/,/^(?:swimlane-beta\b)/,/^(?:graph\b)/,/^(?:flowchart\b)/,/^(?:subgraph\b)/,/^(?:end\b\s*)/,/^(?:_self\b)/,/^(?:_blank\b)/,/^(?:_parent\b)/,/^(?:_top\b)/,/^(?:(\r?\n)*\s*\n)/,/^(?:\s*LR\b)/,/^(?:\s*RL\b)/,/^(?:\s*TB\b)/,/^(?:\s*BT\b)/,/^(?:\s*TD\b)/,/^(?:\s*BR\b)/,/^(?:\s*<)/,/^(?:\s*>)/,/^(?:\s*\^)/,/^(?:\s*v\b)/,/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:.*direction\s+TD[^\n]*)/,/^(?:[^\s\"]+@(?=[^\{\"]))/,/^(?:[0-9]+)/,/^(?:#)/,/^(?::::)/,/^(?::)/,/^(?:&)/,/^(?:;)/,/^(?:,)/,/^(?:\*)/,/^(?:\s*[xo<]?--+[-xo>]\s*)/,/^(?:\s*[xo<]?--\s*)/,/^(?:[^-]|-(?!-)+)/,/^(?:\s*[xo<]?==+[=xo>]\s*)/,/^(?:\s*[xo<]?==\s*)/,/^(?:[^=]|=(?!))/,/^(?:\s*[xo<]?-?\.+-[xo>]?\s*)/,/^(?:\s*[xo<]?-\.\s*)/,/^(?:[^\.]|\.(?!))/,/^(?:\s*~~[\~]+\s*)/,/^(?:[-/\)][\)])/,/^(?:[^\(\)\[\]\{\}]|!\)+)/,/^(?:\(-)/,/^(?:\]\))/,/^(?:\(\[)/,/^(?:\]\])/,/^(?:\[\[)/,/^(?:\[\|)/,/^(?:>)/,/^(?:\)\])/,/^(?:\[\()/,/^(?:\)\)\))/,/^(?:\(\(\()/,/^(?:[\\(?=\])][\]])/,/^(?:\/(?=\])\])/,/^(?:\/(?!\])|\\(?!\])|[^\\\[\]\(\)\{\}\/]+)/,/^(?:\[\/)/,/^(?:\[\\)/,/^(?:<)/,/^(?:>)/,/^(?:\^)/,/^(?:\\\|)/,/^(?:v\b)/,/^(?:\*)/,/^(?:#)/,/^(?:&)/,/^(?:([A-Za-z0-9!"\#$%&'*+\.`?\\_\/]|-(?=[^\>\-\.])|(?!))+)/,/^(?:-)/,/^(?:[\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]|[\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]|[\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5]|[\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA]|[\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE]|[\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA]|[\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0]|[\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977]|[\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2]|[\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A]|[\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39]|[\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8]|[\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C]|[\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C]|[\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99]|[\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0]|[\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D]|[\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3]|[\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10]|[\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1]|[\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81]|[\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3]|[\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6]|[\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A]|[\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081]|[\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D]|[\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0]|[\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310]|[\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C]|[\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711]|[\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7]|[\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C]|[\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16]|[\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF]|[\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC]|[\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D]|[\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D]|[\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3]|[\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F]|[\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128]|[\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184]|[\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3]|[\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6]|[\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE]|[\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C]|[\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D]|[\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC]|[\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B]|[\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788]|[\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805]|[\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB]|[\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28]|[\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5]|[\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4]|[\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E]|[\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D]|[\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36]|[\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D]|[\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC]|[\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF]|[\uFFD2-\uFFD7\uFFDA-\uFFDC])/,/^(?:\|)/,/^(?:\|)/,/^(?:\))/,/^(?:\()/,/^(?:\])/,/^(?:\[)/,/^(?:(\}))/,/^(?:\{)/,/^(?:[^\[\]\(\)\{\}\|\"]+)/,/^(?:")/,/^(?:(\r?\n)+)/,/^(?:[^\S\n\r]+)/,/^(?:$)/],+conditions: {"shapeDataEndBracket":{"rules":[21,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"shapeDataStr":{"rules":[9,10,21,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"shapeData":{"rules":[8,11,12,21,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"callbackargs":{"rules":[17,18,21,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"callbackname":{"rules":[14,15,16,21,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"href":{"rules":[21,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"click":{"rules":[21,24,33,34,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"dottedEdgeText":{"rules":[21,24,76,78,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"thickEdgeText":{"rules":[21,24,73,75,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"edgeText":{"rules":[21,24,70,72,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"trapText":{"rules":[21,24,79,82,84,86,90,92,93,94,95,96,97,110,112,114,116],"inclusive":false},"ellipseText":{"rules":[21,24,79,80,81,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"text":{"rules":[21,24,79,82,83,84,85,86,89,90,91,92,96,97,109,110,111,112,113,114,115,116,117],"inclusive":false},"vertex":{"rules":[21,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"dir":{"rules":[21,24,45,46,47,48,49,50,51,52,53,54,55,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"acc_descr_multiline":{"rules":[5,6,21,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"acc_descr":{"rules":[3,21,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"acc_title":{"rules":[1,21,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"md_string":{"rules":[19,20,21,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"string":{"rules":[21,22,23,24,79,82,84,86,90,92,96,97,110,112,114,116],"inclusive":false},"INITIAL":{"rules":[0,2,4,7,13,21,24,25,26,27,28,29,30,31,32,35,36,37,38,39,40,41,42,43,44,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,73,74,76,77,79,82,84,86,87,88,90,92,96,97,98,99,100,101,102,103,104,105,106,107,108,110,112,114,116,118,119,120,121],"inclusive":true}}+});+return lexer;+})();+parser.lexer = lexer;+function Parser () {+ this.yy = {};+}+Parser.prototype = parser;parser.Parser = Parser;+return new Parser;+})();+parser.parser = parser+export default parserdiff --git a/packages/mermaid/src/upstream/preprocess.ts b/packages/mermaid/src/upstream/preprocess.tsnew file mode 100644index 000000000..5fde76f37--- /dev/null+++ b/packages/mermaid/src/upstream/preprocess.ts@@ -0,0 +1,62 @@+// @ts-nocheck+// Copied by `bun run generate:mermaid-sources` from [email protected]+// (https://raw.githubusercontent.com/mermaid-js/mermaid/1fb7869866dd619168d840291c9c54b4f129758b/packages/mermaid/src/preprocess.ts)+// (https://raw.githubusercontent.com/mermaid-js/mermaid/1fb7869866dd619168d840291c9c54b4f129758b/packages/mermaid/src/utils.ts)+// Copyright (c) 2014 - 2022 Knut Sveidqvist. MIT License; see MERMAID-LICENSE.txt.+// Do not edit: change the pinned release in tools/generate/mermaid-sources and regenerate.+import { directiveRegex } from './regexes'++export const cleanupText = (code: string) => {+ return (+ code+ // parser problems on CRLF ignore all CR and leave LF;;+ .replace(/\r\n?/g, '\n')+ // clean up html tags so that all attributes use single quotes, parser throws error on double quotes+ .replace(+ /<(\w+)([^>]*)>/g,+ (match, tag, attributes) => '<' + tag + attributes.replace(/="([^"]*)"/g, "='$1'") + '>'+ )+ );+};++export const removeDirectives = function (text: string): string {+ return text.replace(directiveRegex, '');+};++/**+ * @param text - text to be encoded+ * @returns+ */+export const encodeEntities = function (text: string): string {+ let txt = text;++ txt = txt.replace(/style.*:\S*#.*;/g, function (s): string {+ return s.substring(0, s.length - 1);+ });+ txt = txt.replace(/classDef.*:\S*#.*;/g, function (s): string {+ return s.substring(0, s.length - 1);+ });++ txt = txt.replace(/#\w+;/g, function (s) {+ const innerTxt = s.substring(1, s.length - 1);++ const isInt = /^\+?\d+$/.test(innerTxt);+ if (isInt) {+ return 'fl°°' + innerTxt + '¶ß';+ } else {+ return 'fl°' + innerTxt + '¶ß';+ }+ });++ return txt;+};++/**+ * Partially reverts encoding done via {@link encodeEntities}+ *+ * @param text - text to be decoded+ * @returns+ */+export const decodeEntities = function (text: string): string {+ return text.replace(/fl°°/g, '&#').replace(/fl°/g, '&').replace(/¶ß/g, ';');+};diff --git a/packages/mermaid/src/upstream/regexes.ts b/packages/mermaid/src/upstream/regexes.tsnew file mode 100644index 000000000..7c0378618--- /dev/null+++ b/packages/mermaid/src/upstream/regexes.ts@@ -0,0 +1,199 @@+// @ts-nocheck+// Copied by `bun run generate:mermaid-sources` from [email protected]+// (https://raw.githubusercontent.com/mermaid-js/mermaid/1fb7869866dd619168d840291c9c54b4f129758b/packages/mermaid/src/diagram-api/regexes.ts)+// Copyright (c) 2014 - 2022 Knut Sveidqvist. MIT License; see MERMAID-LICENSE.txt.+// Do not edit: change the pinned release in tools/generate/mermaid-sources and regenerate.+// Match Jekyll-style front matter blocks (https://jekyllrb.com/docs/front-matter/).+// Based on regex used by Jekyll: https://github.com/jekyll/jekyll/blob/6dd3cc21c40b98054851846425af06c64f9fb466/lib/jekyll/document.rb#L10+// Note that JS doesn't support the "\A" anchor, which means we can't use+// multiline mode.+// Relevant YAML spec: https://yaml.org/spec/1.2.2/#914-explicit-documents+// The \1 backreference anchors closing `---` to the same indent as the opening one, guards against indented `---` inside multi-line YAML scalars (#7613).+// Kept byte-for-byte as released: it is part of the published surface. It backtracks quadratically+// (see `matchFrontMatter` below), so internal hot paths must use `matchFrontMatter` instead of+// matching with this regex directly.+export const frontMatterRegex = /^([^\S\n\r]*)-{3}\s*[\n\r](.*?)[\n\r]\1-{3}\s*[\n\r]+/s;++export const directiveRegex =+ /%{2}{\s*(?:(\w+)\s*:|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi;++// Kept byte-for-byte as released: it is part of the published surface, and consumers replace with+// `'\n'` — a pattern change (capture groups, lookbehind) would silently change their output or throw+// at module load on older engines. It backtracks quadratically on deep indents, so internal hot+// paths must use `stripAnyComments` below instead of replacing with this regex directly.+export const anyCommentRegex = /\s*%%.*\n/gm;++/** One character, tested against the same class `\s` means inside `anyCommentRegex`. */+const whitespace = /\s/;++/**+ * Strip `%%` comment runs exactly like `text.replace(anyCommentRegex, '\n')`, in linear time.+ *+ * A scanner rather than a regex, because no variant of this pattern is linear. Every regex form+ * carries a `\s*` that can cross newlines, and `/m` gives the engine a candidate start at each+ * line, so an all-whitespace document has the match attempt rescan the remaining run once per+ * line. Two shapes are quadratic in the released pattern and in the guarded `(^|\S)\s*%%.*\n`+ * that replaced it, both inside the default 50k `maxTextSize`:+ *+ * ```+ * ('\n' + ' '.repeat(4)).repeat(10_000) all whitespace, many lines 256ms+ * '%%' + 'x%%'.repeat(16_000) no terminating newline 339ms+ * ```+ *+ * against 0.1ms for ordinary diagram text of the same size. The guard cut the constant roughly+ * 40x but left the exponent alone, which is what CodeQL and the CWE-1333 review both caught.+ *+ * The scan walks forward once. For each `%%` it takes the line's terminating newline as the end+ * of the match — `.` never matches a newline, so the regex ends at that same character — and+ * extends left over the preceding whitespace run, never past the previous match. Each character+ * is visited at most twice, so the work is linear in the input and independent of how the+ * whitespace is arranged.+ *+ * A `%%` with no newline after it is left alone, because `%%.*\n` cannot match without one.+ */+export const stripAnyComments = (text: string): string => {+ let out = '';+ // Everything before this index has been emitted or dropped; also the floor for the leftward+ // whitespace scan, which is what `lastIndex` does for the global regex.+ let consumed = 0;+ let searchFrom = 0;++ while (searchFrom < text.length) {+ const marker = text.indexOf('%%', searchFrom);+ if (marker === -1) {+ break;+ }+ const lineEnd = text.indexOf('\n', marker);+ if (lineEnd === -1) {+ // No newline left in the string, so this `%%` and every later one cannot match.+ break;+ }+ let start = marker;+ while (start > consumed && whitespace.test(text[start - 1])) {+ start--;+ }+ out += text.slice(consumed, start) + '\n';+ consumed = lineEnd + 1;+ searchFrom = consumed;+ }++ return out + text.slice(consumed);+};++/** True for the characters `[\n\r]` means in `frontMatterRegex`. */+const isLineBreak = (char: string | undefined): boolean => char === '\n' || char === '\r';++/**+ * Index of the last `[\n\r]` in the whitespace run starting at `from`, or `-1` if the run holds+ * none. This is where a greedy `\s*[\n\r]+` stops: `\s*` takes the whole run, then gives+ * characters back until the next one is a line break.+ */+const lastLineBreakInWhitespaceRun = (text: string, from: number): number => {+ let index = -1;+ for (let i = from; i < text.length && whitespace.test(text[i]); i++) {+ if (isLineBreak(text[i])) {+ index = i;+ }+ }+ return index;+};++export interface FrontMatterMatch {+ /** The horizontal indent of the opening fence — `frontMatterRegex`'s capture group 1. */+ indent: string;+ /** The YAML body between the fences — capture group 2. */+ body: string;+ /** Length of the whole match, so callers can slice the front matter off. */+ length: number;+}++/**+ * Locate a front matter block exactly like `text.match(frontMatterRegex)`, in linear time.+ *+ * A scanner rather than a regex, because `frontMatterRegex` is ambiguous: the opening `\s*[\n\r]`+ * lets `\s*` consume line breaks as well, so every failed search for a closing fence backtracks+ * into it. Each of the O(n) split points then rescans the lazy body, which is quadratic overall —+ * on `'---\n' + ' \n'.repeat(n)`, well inside the default 50k `maxTextSize`:+ *+ * ```+ * n = 4_000 38ms+ * n = 8_000 161ms+ * n = 16_000 619ms+ * ```+ *+ * Removing the ambiguity is not behaviour-preserving, so the scanner reproduces the+ * backtracking result rather than a tidier reading of it. The engine tries the *longest* opening+ * first and shortens it one line break at a time until the rest matches, which is equivalent to:+ *+ * 1. Take the closing fences that could terminate a block — a line break, `indent---`, then at+ * least one more line break in the following whitespace run.+ * 2. The opening ends at the **last** line break of the run after `---` that still leaves a+ * closing fence after it, since a longer opening is preferred but must leave one behind.+ * 3. The body ends at the **first** closing fence after that, because the body is lazy.+ *+ * This is why `'---\n\n---\n\nMORE\n---\n'` is stripped whole: the opening swallows both leading+ * line breaks, so the second `---` lands inside the body and only the third one can close.+ *+ * Two forward passes, each visiting a character a bounded number of times: the trailing+ * whitespace runs of two closing fences cannot overlap, since `---` separates them.+ */+export const matchFrontMatter = (text: string): FrontMatterMatch | undefined => {+ let cursor = 0;+ while (cursor < text.length && whitespace.test(text[cursor]) && !isLineBreak(text[cursor])) {+ cursor++;+ }+ const indent = text.slice(0, cursor);++ if (!text.startsWith('---', cursor)) {+ return undefined;+ }++ // Candidate opening ends: the line breaks of the whitespace run after the opening `---`.+ const openingEnds: number[] = [];+ for (let i = cursor + 3; i < text.length && whitespace.test(text[i]); i++) {+ if (isLineBreak(text[i])) {+ openingEnds.push(i);+ }+ }+ if (openingEnds.length === 0) {+ return undefined;+ }++ const closingFence = `${indent}---`;+ // A closing fence is only usable if the trailing `\s*[\n\r]+` matches too.+ const closingEnd = (i: number): number =>+ isLineBreak(text[i]) && text.startsWith(closingFence, i + 1)+ ? lastLineBreakInWhitespaceRun(text, i + 1 + closingFence.length)+ : -1;++ const earliestBodyStart = openingEnds[0] + 1;++ let lastClosingFence = -1;+ for (let i = earliestBodyStart; i < text.length; i++) {+ if (closingEnd(i) !== -1) {+ lastClosingFence = i;+ }+ }+ if (lastClosingFence === -1) {+ return undefined;+ }++ // Longest opening that still leaves a closing fence behind. One always exists: every closing+ // fence sits at or after `earliestBodyStart`, which is past `openingEnds[0]`.+ let openingEnd = openingEnds[0];+ for (const candidate of openingEnds) {+ if (candidate < lastClosingFence) {+ openingEnd = candidate;+ }+ }++ const bodyStart = openingEnd + 1;+ for (let i = bodyStart; i <= lastClosingFence; i++) {+ const matchEnd = closingEnd(i);+ if (matchEnd !== -1) {+ return { indent, body: text.slice(bodyStart, i), length: matchEnd + 1 };+ }+ }++ return undefined;+};diff --git a/packages/mermaid/tests/detect.test.ts b/packages/mermaid/tests/detect.test.tsnew file mode 100644index 000000000..cf99c22b4--- /dev/null+++ b/packages/mermaid/tests/detect.test.ts@@ -0,0 +1,19 @@+import { describe, expect, test } from 'bun:test'++import { detectMermaidDiagram } from '@open-pencil/mermaid'++describe('detectMermaidDiagram', () => {+ test('recognises flowcharts after front matter, directives, and comments', () => {+ expect(detectMermaidDiagram('flowchart LR\nA-->B')).toBe('flowchart')+ expect(detectMermaidDiagram(' graph TD;A-->B')).toBe('flowchart')+ expect(detectMermaidDiagram('---\ntitle: T\n---\n%%{init: {}}%%\n%% note\ngraph TD\nA')).toBe(+ 'flowchart'+ )+ })++ test('returns null for other diagrams and for text that is not Mermaid', () => {+ expect(detectMermaidDiagram('sequenceDiagram\nA->>B: hi')).toBeNull()+ expect(detectMermaidDiagram('graphical user interfaces')).toBeNull()+ expect(detectMermaidDiagram('Hello')).toBeNull()+ })+})diff --git a/packages/mermaid/tests/flowchart/parse.test.ts b/packages/mermaid/tests/flowchart/parse.test.tsnew file mode 100644index 000000000..c11da006d--- /dev/null+++ b/packages/mermaid/tests/flowchart/parse.test.ts@@ -0,0 +1,234 @@+import { describe, expect, test } from 'bun:test'++import { parseFlowchart, type FlowEdge, type Flowchart } from '@open-pencil/mermaid'++function node(chart: Flowchart, id: string) {+ const found = chart.nodes.find((candidate) => candidate.id === id)+ if (!found) throw new Error(`No node ${id}`)+ return found+}++function link(edge: FlowEdge) {+ return [edge.from, edge.to, edge.startArrow, edge.endArrow, edge.stroke, edge.length]+}++// Cases follow Mermaid's own parser specs (`diagrams/flowchart/parser/flow-*.spec.js`), read+// through our model instead of Mermaid's `FlowDB`.+describe('parseFlowchart', () => {+ test('reads the direction in each spelling', () => {+ expect(parseFlowchart('graph TD;A-->B').direction).toBe('TB')+ expect(parseFlowchart('graph >;A-->B').direction).toBe('LR')+ expect(parseFlowchart('graph <;A-->B').direction).toBe('RL')+ expect(parseFlowchart('graph ^;A-->B').direction).toBe('BT')+ expect(parseFlowchart('graph v;A-->B').direction).toBe('TB')+ expect(parseFlowchart('flowchart LR\nA-->B').direction).toBe('LR')+ expect(parseFlowchart('flowchart\nA-->B').direction).toBe('TB')+ })++ test('gives each bracket form its shape and label', () => {+ const chart = parseFlowchart(`flowchart TD+ a[square] --> b(round) --> c([stadium]) --> d[[subroutine]] --> e[(cylinder)]+ f((circle)) --> g{diamond} --> h{{hexagon}} --> i>odd] --> j(((double)))+ k[/lean right/] --> l[\\lean left\\] --> m[/trapezoid\\] --> n[\\inverted/]+ o(-ellipse-) --> p`)+ const shapes = Object.fromEntries(chart.nodes.map((n) => [n.id, n.shape]))+ expect(shapes).toEqual({+ a: 'rect',+ b: 'rounded',+ c: 'stadium',+ d: 'fr-rect',+ e: 'cyl',+ f: 'circle',+ g: 'diam',+ h: 'hex',+ i: 'odd',+ j: 'dbl-circ',+ k: 'lean-r',+ l: 'lean-l',+ m: 'trap-b',+ n: 'trap-t',+ o: 'ellipse',+ p: 'rect'+ })+ expect(node(chart, 'g').label).toEqual({ text: 'diamond', format: 'text' })+ // A node written without brackets is labelled with its id.+ expect(node(chart, 'p').label).toEqual({ text: 'p', format: 'text' })+ })++ test('takes the shape and label from `@{ … }` data, aliases included', () => {+ const chart = parseFlowchart(`flowchart TD+ a@{ shape: doc, label: "Spec" }+ b@{ shape: database }+ c@{+ shape: diamond+ label: Choose+ }+ a --> b`)+ expect(node(chart, 'a').shape).toBe('doc')+ expect(node(chart, 'a').label.text).toBe('Spec')+ expect(node(chart, 'b').shape).toBe('cyl')+ expect(node(chart, 'c').shape).toBe('diam')+ expect(node(chart, 'c').label.text).toBe('Choose')+ expect(() => parseFlowchart('flowchart TD\na@{ shape: blob }')).toThrow('No such shape: blob')+ })++ test('reads arrowheads, strokes, and lengths', () => {+ const edges = parseFlowchart(`graph TD+ A-->B+ A---B+ A-.->B+ A==>B+ A~~~B+ A--oB+ A--xB+ A<-->B+ A o--o B+ A x==x B+ A---->B+ A-...->B`).edges+ expect(edges.map(link)).toEqual([+ ['A', 'B', 'none', 'arrow', 'normal', 1],+ ['A', 'B', 'none', 'none', 'normal', 1],+ ['A', 'B', 'none', 'arrow', 'dotted', 1],+ ['A', 'B', 'none', 'arrow', 'thick', 1],+ ['A', 'B', 'none', 'none', 'invisible', 1],+ ['A', 'B', 'none', 'circle', 'normal', 1],+ ['A', 'B', 'none', 'cross', 'normal', 1],+ ['A', 'B', 'arrow', 'arrow', 'normal', 1],+ ['A', 'B', 'circle', 'circle', 'normal', 1],+ ['A', 'B', 'cross', 'cross', 'thick', 1],+ ['A', 'B', 'none', 'arrow', 'normal', 3],+ ['A', 'B', 'none', 'arrow', 'dotted', 3]+ ])+ })++ test('reads edge labels in both forms and fans `&` out', () => {+ const chart = parseFlowchart(`graph LR+ A -- yes --> B+ A -->|no| C+ A & B --> D & E`)+ expect(chart.edges.map((edge) => [edge.from, edge.to, edge.label?.text])).toEqual([+ ['A', 'B', 'yes'],+ ['A', 'C', 'no'],+ ['A', 'D', undefined],+ ['A', 'E', undefined],+ ['B', 'D', undefined],+ ['B', 'E', undefined]+ ])+ })++ test('names an edge by its id, and the id never becomes a node', () => {+ const chart = parseFlowchart(`flowchart LR+ A e1@--> B & C+ e1@{ animate: true }`)+ expect(chart.edges.map((edge) => [edge.id, edge.to])).toEqual([+ ['e1', 'B'],+ ['L_A_C_0', 'C']+ ])+ expect(chart.nodes.map((n) => n.id)).toEqual(['A', 'B', 'C'])+ })++ test('nests subgraphs, gives each node to its innermost one, and keeps their directions', () => {+ const chart = parseFlowchart(`flowchart TB+ c1-->a2+ subgraph one+ a1-->a2+ end+ subgraph two [Second]+ direction LR+ b1-->b2+ subgraph three+ b2-->b3+ end+ end+ subgraph Title with spaces+ x+ end+ one --> two`)+ const subgraphs = chart.subgraphs.map((s) => [s.id, s.title.text, s.members, s.direction])+ expect(subgraphs).toEqual([+ ['one', 'one', ['a2', 'a1'], undefined],+ ['three', 'three', ['b3', 'b2'], undefined],+ ['two', 'Second', ['b1', 'three'], 'LR'],+ ['subGraph3', 'Title with spaces', ['x'], undefined]+ ])+ // Edges may join subgraphs, which are not nodes.+ expect(chart.edges.at(-1)).toMatchObject({ from: 'one', to: 'two' })+ expect(chart.nodes.map((n) => n.id)).not.toContain('one')+ })++ test('collects classes and styles for nodes, subgraphs, and edges', () => {+ const chart = parseFlowchart(`flowchart LR+ A:::hot --> B+ subgraph S+ C+ end+ classDef hot fill:#f96,stroke:#333+ classDef cold,frozen fill:#9cf+ class B cold+ style A stroke-width:4px+ style S fill:#eee+ class S frozen+ linkStyle default stroke:#999+ linkStyle 0 stroke:#f00`)+ expect(node(chart, 'A')).toMatchObject({ classes: ['hot'], styles: ['stroke-width:4px'] })+ expect(node(chart, 'B').classes).toEqual(['cold'])+ expect(chart.classDefs.get('hot')).toEqual(['fill:#f96', 'stroke:#333'])+ expect(chart.classDefs.get('frozen')).toEqual(['fill:#9cf'])+ expect(chart.subgraphs[0]).toMatchObject({ styles: ['fill:#eee'], classes: ['frozen'] })+ expect(chart.edges[0]?.styles).toEqual(['stroke:#999', 'stroke:#f00'])+ expect(() => parseFlowchart('flowchart LR\nA-->B\nlinkStyle 3 stroke:#f00')).toThrow(+ 'out of bounds'+ )+ })++ test('keeps links and tooltips, and ignores callbacks', () => {+ const chart = parseFlowchart(`flowchart LR+ A-->B-->C+ click A "https://example.com" "Docs" _blank+ click B href "https://example.org"+ click C callback "Runs a script"`)+ expect(node(chart, 'A')).toMatchObject({+ link: { href: 'https://example.com', target: '_blank' },+ tooltip: 'Docs'+ })+ expect(node(chart, 'B').link).toEqual({ href: 'https://example.org' })+ expect(node(chart, 'C').link).toBeUndefined()+ expect(node(chart, 'C').tooltip).toBe('Runs a script')+ })++ test('reads text labels as Mermaid draws them, and markdown as written', () => {+ const chart = parseFlowchart(`flowchart LR+ A["Quoted (with) brackets"] --> B[Line<br>break<br/>again]+ B --> C["<b>Bold</b> #quot;text#quot; #9829;"]+ C --> D["\`**Markdown** text\`"]`)+ expect(node(chart, 'A').label.text).toBe('Quoted (with) brackets')+ expect(node(chart, 'B').label.text).toBe('Line\nbreak\nagain')+ expect(node(chart, 'C').label.text).toBe('Bold "text" ♥')+ expect(node(chart, 'D').label).toEqual({ text: '**Markdown** text', format: 'markdown' })+ })++ test('reads the title from front matter and skips directives and comments', () => {+ const chart = parseFlowchart(`---+title: Checkout+config:+ theme: dark+---+%%{init: {"flowchart": {"curve": "basis"}}}%%+flowchart LR+ %% a comment+ A --> B+ accTitle: Steps+ accDescr: The checkout steps`)+ expect(chart.title).toBe('Checkout')+ expect(chart.direction).toBe('LR')+ expect(chart.accessibleTitle).toBe('Steps')+ expect(chart.accessibleDescription).toBe('The checkout steps')+ expect(chart.nodes.map((n) => n.id)).toContain('A')+ })++ test('throws Mermaid’s parse error for text it cannot read', () => {+ expect(() => parseFlowchart('flowchart LR\nA --> ')).toThrow(/^Parse error on line \d+:/)+ expect(() => parseFlowchart('sequenceDiagram\nA->>B: hi')).toThrow()+ })+})diff --git a/packages/mermaid/tsconfig.json b/packages/mermaid/tsconfig.jsonnew file mode 100644index 000000000..537ea362e--- /dev/null+++ b/packages/mermaid/tsconfig.json@@ -0,0 +1,24 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["ES2023", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "declaration": true,+ "declarationDir": "./dist/src",+ "declarationMap": true,+ "outDir": "./dist",+ "rootDir": "./src",+ "skipLibCheck": true,+ "esModuleInterop": true,+ "resolveJsonModule": true,+ "types": ["bun"],+ "paths": {+ "#mermaid/*": ["./src/*"],+ "@open-pencil/mermaid": ["./src/index.ts"]+ }+ },+ "include": ["src/**/*.ts"],+ "exclude": ["node_modules", "dist"]+}diff --git a/packages/mermaid/tsdown.config.ts b/packages/mermaid/tsdown.config.tsnew file mode 100644index 000000000..a1c75b2b1--- /dev/null+++ b/packages/mermaid/tsdown.config.ts@@ -0,0 +1,39 @@+import { defineConfig } from 'tsdown'++export default defineConfig({+ entry: {+ index: './src/index.ts'+ },+ platform: 'neutral',+ format: ['esm'],+ dts: true,+ sourcemap: true,+ hash: false,+ clean: true,+ outDir: './dist',+ treeshake: {+ moduleSideEffects: false+ },+ deps: {+ neverBundle: ['entities', 'parse5', 'valibot', 'yaml', /^node:/],+ onlyBundle: false+ },+ outputOptions: {+ minifyInternalExports: false,+ codeSplitting: {+ groups: [+ {+ test: /(?<!\.d\.c?ts)$/,+ name: (id) => {+ const cleanId = id.split('?')[0]+ const parts = cleanId.split(/[\\/]/g)+ const srcIndex = parts.lastIndexOf('src')+ const file =+ srcIndex >= 0 ? parts.slice(srcIndex + 1).join('/') : (parts.at(-1) ?? 'chunk')+ return `chunks/${file.replace(/\.(ts|tsx)$/, '')}`+ }+ }+ ]+ }+ }+})diff --git a/packages/vue/src/i18n/locales/de/files.json b/packages/vue/src/i18n/locales/de/files.jsonindex 69d8d0f9b..6a4053e7f 100644--- a/packages/vue/src/i18n/locales/de/files.json+++ b/packages/vue/src/i18n/locales/de/files.json@@ -17,6 +17,7 @@"clipboardImagesUnavailableWeb": "Das eingefügte Design enthält {count} Bilder, die in der Web-App nicht geladen werden können. Verwende die Desktop-App, um sie einzuschließen.","clipboardImageFetchFailed": "1 Bild konnte nicht aus Figma abgerufen werden. Prüfe, ob die Quelldatei zugänglich ist, und versuche es erneut.","clipboardImagesFetchFailed": "{count} Bilder konnten nicht aus Figma abgerufen werden. Prüfe, ob die Quelldatei zugänglich ist, und versuche es erneut.",+ "mermaidPasteFailed": "Das Mermaid-Diagramm konnte nicht gelesen werden. {error}","recentFiles": "Zuletzt verwendete Dateien","recentFilesDescription": "Arbeite an einem Entwurf weiter oder beginne einen neuen.","noRecentFiles": "Noch keine zuletzt verwendeten Dateien",diff --git a/packages/vue/src/i18n/locales/es/files.json b/packages/vue/src/i18n/locales/es/files.jsonindex e935880b2..2f999d9f2 100644--- a/packages/vue/src/i18n/locales/es/files.json+++ b/packages/vue/src/i18n/locales/es/files.json@@ -17,6 +17,7 @@"clipboardImagesUnavailableWeb": "El diseño pegado contiene {count} imágenes que no se pueden cargar en la aplicación web. Usa la aplicación de escritorio para incluirlas.","clipboardImageFetchFailed": "No se ha podido obtener 1 imagen de Figma. Comprueba que el archivo de origen sea accesible e inténtalo de nuevo.","clipboardImagesFetchFailed": "No se han podido obtener {count} imágenes de Figma. Comprueba que el archivo de origen sea accesible e inténtalo de nuevo.",+ "mermaidPasteFailed": "No se ha podido leer el diagrama de Mermaid. {error}","recentFiles": "Archivos recientes","recentFilesDescription": "Continúa trabajando en un diseño o crea uno nuevo.","noRecentFiles": "Aún no hay archivos recientes",diff --git a/packages/vue/src/i18n/locales/fr/files.json b/packages/vue/src/i18n/locales/fr/files.jsonindex fa67c6f4f..70a9bf1ef 100644--- a/packages/vue/src/i18n/locales/fr/files.json+++ b/packages/vue/src/i18n/locales/fr/files.json@@ -17,6 +17,7 @@"clipboardImagesUnavailableWeb": "Le design collé contient {count} images qui ne peuvent pas être chargées dans l’application web. Utilisez l’application de bureau pour les inclure.","clipboardImageFetchFailed": "Impossible de récupérer 1 image depuis Figma. Vérifiez que le fichier source est accessible, puis réessayez.","clipboardImagesFetchFailed": "Impossible de récupérer {count} images depuis Figma. Vérifiez que le fichier source est accessible, puis réessayez.",+ "mermaidPasteFailed": "Impossible de lire le diagramme Mermaid. {error}","recentFiles": "Fichiers récents","recentFilesDescription": "Continuez un design ou commencez-en un nouveau.","noRecentFiles": "Aucun fichier récent",diff --git a/packages/vue/src/i18n/locales/it/files.json b/packages/vue/src/i18n/locales/it/files.jsonindex 94f449c39..79fc6428f 100644--- a/packages/vue/src/i18n/locales/it/files.json+++ b/packages/vue/src/i18n/locales/it/files.json@@ -17,6 +17,7 @@"clipboardImagesUnavailableWeb": "Il design incollato contiene {count} immagini che non possono essere caricate nell’app web. Usa l’app desktop per includerle.","clipboardImageFetchFailed": "Impossibile recuperare 1 immagine da Figma. Controlla che il file sorgente sia accessibile e riprova.","clipboardImagesFetchFailed": "Impossibile recuperare {count} immagini da Figma. Controlla che il file sorgente sia accessibile e riprova.",+ "mermaidPasteFailed": "Impossibile leggere il diagramma Mermaid. {error}","recentFiles": "File recenti","recentFilesDescription": "Continua a lavorare su un progetto o iniziane uno nuovo.","noRecentFiles": "Nessun file recente",diff --git a/packages/vue/src/i18n/locales/ja/files.json b/packages/vue/src/i18n/locales/ja/files.jsonindex 0234d7081..58c2691e9 100644--- a/packages/vue/src/i18n/locales/ja/files.json+++ b/packages/vue/src/i18n/locales/ja/files.json@@ -17,6 +17,7 @@"clipboardImagesUnavailableWeb": "貼り付けたデザインには、ウェブアプリで読み込めない画像が{count}件含まれています。それらの画像を含めるにはデスクトップアプリを使用してください。","clipboardImageFetchFailed": "Figmaから画像1件を取得できませんでした。元のファイルにアクセスできることを確認して、もう一度お試しください。","clipboardImagesFetchFailed": "Figmaから画像{count}件を取得できませんでした。元のファイルにアクセスできることを確認して、もう一度お試しください。",+ "mermaidPasteFailed": "Mermaid の図を読み込めませんでした。{error}","recentFiles": "最近使用したファイル","recentFilesDescription": "デザインの作業を続けるか、新しく始めます。","noRecentFiles": "最近使用したファイルはありません",diff --git a/packages/vue/src/i18n/locales/pl/files.json b/packages/vue/src/i18n/locales/pl/files.jsonindex 952397aec..61debe500 100644--- a/packages/vue/src/i18n/locales/pl/files.json+++ b/packages/vue/src/i18n/locales/pl/files.json@@ -17,6 +17,7 @@"clipboardImagesUnavailableWeb": "Wklejony projekt zawiera {count} obrazy, których nie można wczytać w aplikacji internetowej. Użyj aplikacji komputerowej, aby je dołączyć.","clipboardImageFetchFailed": "Nie udało się pobrać 1 obrazu z Figmy. Sprawdź, czy plik źródłowy jest dostępny, i spróbuj ponownie.","clipboardImagesFetchFailed": "Nie udało się pobrać {count} obrazów z Figmy. Sprawdź, czy plik źródłowy jest dostępny, i spróbuj ponownie.",+ "mermaidPasteFailed": "Nie udało się odczytać diagramu Mermaid. {error}","recentFiles": "Ostatnie pliki","recentFilesDescription": "Kontynuuj pracę nad projektem lub rozpocznij nowy.","noRecentFiles": "Brak ostatnich plików",diff --git a/packages/vue/src/i18n/locales/ru/files.json b/packages/vue/src/i18n/locales/ru/files.jsonindex 06000b666..1817d120b 100644--- a/packages/vue/src/i18n/locales/ru/files.json+++ b/packages/vue/src/i18n/locales/ru/files.json@@ -17,6 +17,7 @@"clipboardImagesUnavailableWeb": "Вставленный дизайн содержит {count} изображений, которые нельзя загрузить в веб-приложении. Используйте настольное приложение, чтобы включить их.","clipboardImageFetchFailed": "Не удалось получить 1 изображение из Figma. Проверьте доступность исходного файла и повторите попытку.","clipboardImagesFetchFailed": "Не удалось получить {count} изображений из Figma. Проверьте доступность исходного файла и повторите попытку.",+ "mermaidPasteFailed": "Не удалось прочитать диаграмму Mermaid. {error}","recentFiles": "Недавние файлы","recentFilesDescription": "Продолжите работу над дизайном или начните новый.","noRecentFiles": "Недавних файлов пока нет",diff --git a/packages/vue/src/i18n/locales/zh-cn/files.json b/packages/vue/src/i18n/locales/zh-cn/files.jsonindex 72210265a..9b3ba7892 100644--- a/packages/vue/src/i18n/locales/zh-cn/files.json+++ b/packages/vue/src/i18n/locales/zh-cn/files.json@@ -17,6 +17,7 @@"clipboardImagesUnavailableWeb": "粘贴的设计包含 {count} 张无法在网页应用中加载的图片。请使用桌面应用以包含这些图片。","clipboardImageFetchFailed": "无法从 Figma 获取 1 张图片。请检查源文件是否可访问,然后重试。","clipboardImagesFetchFailed": "无法从 Figma 获取 {count} 张图片。请检查源文件是否可访问,然后重试。",+ "mermaidPasteFailed": "无法读取 Mermaid 图表。{error}","recentFiles": "最近使用的文件","recentFilesDescription": "继续编辑设计或新建设计。","noRecentFiles": "暂无最近使用的文件",diff --git a/packages/vue/src/i18n/messages/files.ts b/packages/vue/src/i18n/messages/files.tsindex 0cca590b5..1500d2361 100644--- a/packages/vue/src/i18n/messages/files.ts+++ b/packages/vue/src/i18n/messages/files.ts@@ -27,6 +27,7 @@ export const filesMessageDefaults = {clipboardImagesFetchFailed: params('Failed to fetch {count} images from Figma. Check that the source file is accessible and try again.'),+ mermaidPasteFailed: params('Could not read the Mermaid diagram. {error}'),recentFiles: 'Recent files',recentFilesDescription: 'Continue working on a design or start a new one.',noRecentFiles: 'No recent files yet',diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex a837c1df8..ef291e8dc 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -303,7 +303,7 @@ The CLI defaults the filesystem root to the home directory on Windows and the cu1. **Find or open a document** — `list_documents` for open tabs and their IDs; `open_file { path }` within the effective filesystem root (`list_recent_files` lists recently opened files there), or `new_document {}`. Pass `document_id` and `page_id` explicitly instead of relying on the active tab; `activate_document { document_id }` brings a tab to the front when the user should see it.2. **Query** — `get_page_tree`, `find_nodes`, `query_nodes`, `get_node`, `list_pages`, `get_current_page`.3. **Inspect** — `get_jsx`, `diff_jsx`, `diff_create`, `diff_visual`, `describe`, `export_image`, `export_svg`, `export_pdf`.-4. **Modify** — `render`, `batch_update`, `update_node`, `set_fill`, `set_layout`, `create_shape`, `import_svg`, etc.+4. **Modify** — `render`, `batch_update`, `update_node`, `set_fill`, `set_layout`, `create_shape`, `import_svg`, etc. For a flowchart, write it as Mermaid and call `import_mermaid { mermaid }`: it lays out FigJam shapes, sections, and connectors without overlaps and returns each node's layer id, instead of placing shapes and connectors by hand.5. **Save/export** — `save_file`, `export_image`, `export_svg`, `export_pdf`, or CLI `export`.6. **Close** — `close_file { document_id, unsaved }` closes a document tab after the workflow. With unsaved changes it fails unless `unsaved` is `"save"` or `"discard"`; automation never prompts in the app.diff --git a/src/app/editor/clipboard/paste/content.ts b/src/app/editor/clipboard/paste/content.tsindex 92e1fb913..71051d4d2 100644--- a/src/app/editor/clipboard/paste/content.ts+++ b/src/app/editor/clipboard/paste/content.ts@@ -1,6 +1,10 @@import type { Editor } from '@open-pencil/core'import { isSVGMarkup } from '@open-pencil/core/io/formats/svg'+import { detectMermaidDiagram } from '@open-pencil/mermaid'import type { Vector } from '@open-pencil/scene-graph/primitives'+import { filesMessages } from '@open-pencil/vue/i18n'++import { toast } from '@/app/shell/ui'import { matchingClipboardSnapshot } from '../memory'@@ -36,3 +40,40 @@ export async function pasteSVGText(const { x, y } = pastePoint(editor, cursorPos)return editor.pasteSVG(text, x, y)}++/** Whether pasted text becomes layers of its own, as SVG markup and Mermaid diagrams do. */+export function isLayerText(text: string): boolean {+ return isSVGMarkup(text) || detectMermaidDiagram(text) !== null+}++/**+ * Paste a Mermaid flowchart as FigJam layers laid out around the point; false when the text is+ * not one. A flowchart Mermaid cannot read reports why, its first line being Mermaid's summary.+ */+export async function pasteMermaidText(+ editor: Editor,+ text: string,+ cursorPos?: Vector+): Promise<boolean> {+ if (!detectMermaidDiagram(text)) return false+ const { x, y } = pastePoint(editor, cursorPos)+ try {+ return await editor.pasteMermaid(text, x, y)+ } catch (error) {+ const reason = error instanceof Error ? (error.message.split('\n')[0] ?? '') : ''+ toast.error(filesMessages.get().mermaidPasteFailed({ error: reason }))+ return true+ }+}++/** Paste text that becomes layers of its own; false for any other text. */+export async function pasteLayerText(+ editor: Editor,+ text: string,+ cursorPos?: Vector+): Promise<boolean> {+ return (+ (await pasteSVGText(editor, text, cursorPos)) ||+ (await pasteMermaidText(editor, text, cursorPos))+ )+}diff --git a/src/app/editor/clipboard/system/browser.ts b/src/app/editor/clipboard/system/browser.tsindex cb0166135..95b2ae969 100644--- a/src/app/editor/clipboard/system/browser.ts+++ b/src/app/editor/clipboard/system/browser.ts@@ -10,7 +10,7 @@ import {getInMemoryClipboardHTML,setInMemoryClipboardPayload} from '@/app/editor/clipboard/memory'-import { pasteClipboardHTML, pasteSVGText } from '@/app/editor/clipboard/paste/content'+import { pasteClipboardHTML, pasteLayerText } from '@/app/editor/clipboard/paste/content'import type {BrowserClipboardIO,BrowserClipboardReadResult,@@ -109,7 +109,7 @@ async function pasteSelection(await pasteClipboardHTML(store, result.html, cursorPos)return true}- return result.text !== null && (await pasteSVGText(store, result.text, cursorPos))+ return result.text !== null && (await pasteLayerText(store, result.text, cursorPos))}const memoryHTML = getInMemoryClipboardHTML()diff --git a/src/app/editor/clipboard/system/tauri.ts b/src/app/editor/clipboard/system/tauri.tsindex f2e3dac5e..1121a9830 100644--- a/src/app/editor/clipboard/system/tauri.ts+++ b/src/app/editor/clipboard/system/tauri.ts@@ -8,7 +8,7 @@ import {getInMemoryClipboardHTML,setInMemoryClipboardPayload} from '@/app/editor/clipboard/memory'-import { pasteClipboardHTML, pasteSVGText } from '@/app/editor/clipboard/paste/content'+import { pasteClipboardHTML, pasteLayerText } from '@/app/editor/clipboard/paste/content'import type { SystemClipboard } from '@/app/editor/clipboard/system/types'import {readTauriClipboardText,@@ -45,7 +45,7 @@ async function pasteSelection(store: EditorStore, cursorPos?: Vector): Promise<bawait pasteClipboardHTML(store, text, cursorPos)return true}- if (text && (await pasteSVGText(store, text, cursorPos))) return true+ if (text && (await pasteLayerText(store, text, cursorPos))) return trueconst matchingMemoryHTML = getInMemoryClipboardHTML(text ?? '')if (matchingMemoryHTML && isDesignClipboardHTML(matchingMemoryHTML)) {await pasteClipboardHTML(store, matchingMemoryHTML, cursorPos)diff --git a/src/app/shell/keyboard/clipboard.ts b/src/app/shell/keyboard/clipboard.tsindex 37fbd7005..bf413e9fb 100644--- a/src/app/shell/keyboard/clipboard.ts+++ b/src/app/shell/keyboard/clipboard.ts@@ -1,12 +1,16 @@import { useEventListener } from '@vueuse/core'-import { isSVGMarkup } from '@open-pencil/core/io/formats/svg'import { extractImageFilesFromClipboard } from '@open-pencil/vue/canvas/drop'import type { EditorStore } from '@/app/editor/active-store'import { isDesignClipboardHTML } from '@/app/editor/clipboard/html'import { getInMemoryClipboardHTML } from '@/app/editor/clipboard/memory'-import { pasteClipboardHTML, pastePoint, pasteSVGText } from '@/app/editor/clipboard/paste/content'+import {+ isLayerText,+ pasteClipboardHTML,+ pasteLayerText,+ pastePoint+} from '@/app/editor/clipboard/paste/content'import { browserSystemClipboard } from '@/app/editor/clipboard/system/browser'import { tauriSystemClipboard } from '@/app/editor/clipboard/system/tauri'import type { SystemClipboard } from '@/app/editor/clipboard/system/types'@@ -86,8 +90,8 @@ export function bindEditorClipboard(store: EditorStore) {}const text = e.clipboardData?.getData('text/plain') ?? ''- if (isSVGMarkup(text)) {- void pasteSVGText(store, text, cursorPos)+ if (isLayerText(text)) {+ void pasteLayerText(store, text, cursorPos)return}diff --git a/tests/engine/tauri/file-actions.test.ts b/tests/engine/tauri/file-actions.test.tsindex 0cffb421b..20d3a59ce 100644--- a/tests/engine/tauri/file-actions.test.ts+++ b/tests/engine/tauri/file-actions.test.ts@@ -20,7 +20,7 @@ describe('Tauri file actions', () => {filters: [{name: 'Design file',- extensions: ['fig', 'pen', 'drawio', 'dio', 'html', 'htm', 'xhtml']+ extensions: ['fig', 'pen', 'drawio', 'dio', 'mmd', 'mermaid', 'html', 'htm', 'xhtml']}],multiple: truediff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex ac5fab781..74845dd69 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -169,6 +169,7 @@ ja:files.clipboardImagesFetchFailedja:files.importFailedja:files.importHTMLCSSja:files.importHTMLCSSDescription+ja:files.mermaidPasteFailedja:fonts.downloadFallbackPacksDescriptionja:fonts.unsupportedFormatja:media.getPexelsAPIKey@@ -393,6 +394,7 @@ zh-cn:files.clipboardImagesFetchFailedzh-cn:files.importFailedzh-cn:files.importHTMLCSSzh-cn:files.importHTMLCSSDescription+zh-cn:files.mermaidPasteFailedzh-cn:fonts.downloadFallbackPacksDescriptionzh-cn:fonts.unsupportedFormatzh-cn:media.getPexelsAPIKeydiff --git a/tools/checks/package-quality/src/smoke/scenarios.ts b/tools/checks/package-quality/src/smoke/scenarios.tsindex be9b38457..6a33a5748 100644--- a/tools/checks/package-quality/src/smoke/scenarios.ts+++ b/tools/checks/package-quality/src/smoke/scenarios.ts@@ -36,6 +36,10 @@ export const runtimeScenarios: RuntimeScenario[] = [name: 'draw.io codec',code: 'const { parseDrawIOFile, writeDrawIOFile } = await import(\'@open-pencil/drawio\'); const file = parseDrawIOFile(\'<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/><mxCell id="a" vertex="1" parent="1"/></root></mxGraphModel>\'); if (file?.pages[0]?.cells.length !== 1 || !writeDrawIOFile(file).startsWith(\'<mxfile\')) throw new Error(\'draw.io package smoke failed\')'},+ {+ name: 'Mermaid parser',+ code: "const { parseFlowchart } = await import('@open-pencil/mermaid'); const chart = parseFlowchart('flowchart LR\\n A[Start] --> B{Done?}'); if (chart.direction !== 'LR' || chart.nodes[1]?.shape !== 'diam' || chart.edges.length !== 1) throw new Error('Mermaid package smoke failed')"+ },{name: 'Emit package',code: "const { jsx } = await import('@open-pencil/emit'); const code = jsx.printJSX(jsx.element('Card', [jsx.attribute('wide', null)], [], 0)); if (code !== '<Card wide />') throw new Error('Codegen package smoke failed: ' + code)"diff --git a/tools/checks/package-quality/src/smoke/type-consumer.ts b/tools/checks/package-quality/src/smoke/type-consumer.tsindex c9c4bbebd..4af5b23ba 100644--- a/tools/checks/package-quality/src/smoke/type-consumer.ts+++ b/tools/checks/package-quality/src/smoke/type-consumer.ts@@ -10,6 +10,7 @@ import { parseDrawIOFile, type DrawIOFile } from '@open-pencil/drawio'import { FIG_PACKAGE_STATUS, type FigContainerDocument } from '@open-pencil/fig'import { FIG_KIWI_DEFAULT_VERSION, buildFigKiwi } from '@open-pencil/kiwi/fig/container'import type { GUID as KiwiGUID } from '@open-pencil/kiwi/fig'+import { parseFlowchart, type Flowchart } from '@open-pencil/mermaid'import { parsePenFile, type PenDocument } from '@open-pencil/pen'import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'import type { Color, Vector } from '@open-pencil/scene-graph/primitives'@@ -27,10 +28,11 @@ const penDocument: PenDocument = { version: '1', children: [] }const figDocument: FigContainerDocument = { schemaDeflated: new Uint8Array([1]), dataRaw: new Uint8Array([2]) }const kiwiGuid: KiwiGUID = { sessionID: 1, localID: 2 }const drawioFile: DrawIOFile | null = parseDrawIOFile('<mxfile/>')+const flowchart: Flowchart = parseFlowchart('flowchart LR\\n A --> B')void editorFactory; void editor; void designDocument; void color; void vector; void maybeNodevoid penDocument; void figDocument; void kiwiGuid; void FIG_PACKAGE_STATUSvoid FIG_KIWI_DEFAULT_VERSION; void buildFigKiwi; void parsePenFile; void htmlToDesignDocument-void testIdSelector; void tree; void drawioFile+void testIdSelector; void tree; void drawioFile; void flowchart`export async function verifyTypeConsumer(root: string, consumerDirectory: string): Promise<void> {diff --git a/tools/dev/unit-tests/src/shards.ts b/tools/dev/unit-tests/src/shards.tsindex 006558f49..3949fe67d 100644--- a/tools/dev/unit-tests/src/shards.ts+++ b/tools/dev/unit-tests/src/shards.ts@@ -46,6 +46,7 @@ export const UNIT_TEST_GROUPS = {dom: ['packages/emit/tests','packages/drawio/tests',+ 'packages/mermaid/tests','packages/design-jsx/tests','packages/dom-css/tests','packages/pen/tests',diff --git a/tools/dev/unit-tests/tests/shards.test.ts b/tools/dev/unit-tests/tests/shards.test.tsindex 251e2609c..cb43a1780 100644--- a/tools/dev/unit-tests/tests/shards.test.ts+++ b/tools/dev/unit-tests/tests/shards.test.ts@@ -51,6 +51,7 @@ test('canonical destinations are registered before they hold files', async () =>'design-jsx','emit','drawio',+ 'mermaid','pen','cli','mcp'diff --git a/tools/generate/mermaid-sources/checksums.json b/tools/generate/mermaid-sources/checksums.jsonnew file mode 100644index 000000000..d2ceaf07f--- /dev/null+++ b/tools/generate/mermaid-sources/checksums.json@@ -0,0 +1,8 @@+{+ "comments.ts": "92d537a51f82d93e914fd4e1e641fea08b2159c04cddef865d5939a408886800",+ "flow.jison": "e9891eb4f646140e5110e72ef5f79b099677a265ba1a84884b39a573b56d1c68",+ "flow.js": "f40b33d9c0f5e9bd63cd0e7c7f472245b2ef5a538d43ae72ad4f916b3f360ad5",+ "MERMAID-LICENSE.txt": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80",+ "preprocess.ts": "88aaa6aee18b53ef5f15525b85c14816652b2bd5cfcdb8a83912051bf7de924f",+ "regexes.ts": "de3b61bad00ba921a9dccef5b86c842c7a0c1d8d6584f867aea723a7ef0c2168"+}diff --git a/tools/generate/mermaid-sources/package.json b/tools/generate/mermaid-sources/package.jsonnew file mode 100644index 000000000..fbe332034--- /dev/null+++ b/tools/generate/mermaid-sources/package.json@@ -0,0 +1,19 @@+{+ "name": "@open-pencil/mermaid-sources-tools",+ "private": true,+ "type": "module",+ "imports": {+ "#mermaid-sources/*": "./src/*.ts"+ },+ "scripts": {+ "test": "bun test tests"+ },+ "dependencies": {+ "jison": "0.4.18",+ "typescript": "~5.8.3"+ },+ "devDependencies": {+ "@open-pencil/package-artifacts-tools": "workspace:*",+ "valibot": "^1.5.0"+ }+}diff --git a/tools/generate/mermaid-sources/src/checksums.ts b/tools/generate/mermaid-sources/src/checksums.tsnew file mode 100644index 000000000..118124a1a--- /dev/null+++ b/tools/generate/mermaid-sources/src/checksums.ts@@ -0,0 +1,19 @@+import { createHash } from 'node:crypto'++/**+ * The SHA-256 of each file the generator writes into the upstream folder, by file name, kept+ * beside the generator so a hand edit to a copied or generated file fails a test.+ */+export const CHECKSUMS_FILE = 'tools/generate/mermaid-sources/checksums.json'++export function checksum(content: string): string {+ return createHash('sha256').update(content).digest('hex')+}++export function checksums(files: Map<string, string>): Record<string, string> {+ return Object.fromEntries(+ [...files]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([file, content]) => [file, checksum(content)])+ )+}diff --git a/tools/generate/mermaid-sources/src/extract.ts b/tools/generate/mermaid-sources/src/extract.tsnew file mode 100644index 000000000..e44e6f3b1--- /dev/null+++ b/tools/generate/mermaid-sources/src/extract.ts@@ -0,0 +1,35 @@+import ts from 'typescript'++function declares(statement: ts.Statement, name: string): boolean {+ if (ts.isFunctionDeclaration(statement)) return statement.name?.text === name+ if (!ts.isVariableStatement(statement)) return false+ return statement.declarationList.declarations.some(+ (declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === name+ )+}++/**+ * The top-level declarations of `names` in a TypeScript module, as written, each with the comment+ * before it and exported. Throws when the module no longer declares one, so a release that+ * moves or renames one fails the generator instead of being copied wrongly.+ */+export function extractDeclarations(source: string, path: string, names: string[]): string[] {+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true)+ return names.map((name) => {+ const statement = file.statements.find((candidate) => declares(candidate, name))+ if (!statement) throw new Error(`${path} no longer declares ${name}`)+ const comment = source.slice(statement.getFullStart(), statement.getStart(file)).trim()+ const text = statement.getText(file)+ const exported = ts+ .getModifiers(statement as ts.HasModifiers)+ ?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)+ const declaration = exported ? text : `export ${text}`+ return comment ? `${comment}\n${declaration}` : declaration+ })+}++/** Whether a module imports anything, which a module copied whole must not. */+export function hasImports(source: string, path: string): boolean {+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, false)+ return file.statements.some(ts.isImportDeclaration)+}diff --git a/tools/generate/mermaid-sources/src/generate.ts b/tools/generate/mermaid-sources/src/generate.tsnew file mode 100644index 000000000..ffec55ef5--- /dev/null+++ b/tools/generate/mermaid-sources/src/generate.ts@@ -0,0 +1,131 @@+/**+ * Writes the Mermaid sources `@open-pencil/mermaid` runs into `packages/mermaid/src/upstream`,+ * from the release pinned in `sources.ts`, with Mermaid's licence beside them: each grammar and+ * the parser built from it, the modules copied whole, and the declarations copied out of others.+ *+ * usage: bun generate.ts write the pinned release's sources+ * bun generate.ts --check compare them, and the sources followed by hand, with+ * Mermaid's latest release+ */+import { join } from 'node:path'++import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts-tools'++import { checksums, CHECKSUMS_FILE } from './checksums'+import { extractDeclarations, hasImports } from './extract'+import { parserModule } from './jison'+import { latestRelease } from './releases'+import {+ COPIED_MODULES,+ EXTRACTED_MODULE,+ FOLLOWED_SOURCES,+ GRAMMARS,+ MERMAID_RELEASE,+ provenance,+ sourceURL,+ UPSTREAM_DIR+} from './sources'++async function download(path: string, commit = MERMAID_RELEASE.commit): Promise<string> {+ const url = sourceURL(path, commit)+ const response = await fetch(url)+ if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`)+ return response.text()+}++/**+ * What a release holds of each source, by the name it is compared under: the grammars, the+ * modules copied whole, and the declarations copied out of others.+ */+async function upstream(commit: string): Promise<Map<string, string>> {+ const texts = new Map<string, string>()+ for (const grammar of GRAMMARS) {+ texts.set(`${grammar.parser}.jison`, await download(grammar.source, commit))+ }+ for (const module of COPIED_MODULES) {+ const source = await download(module.source, commit)+ if (hasImports(source, module.source)) {+ throw new Error(`${module.source} now imports other modules; copy declarations out of it`)+ }+ texts.set(module.file, source)+ }+ const declarations: string[] = []+ for (const { source, names } of EXTRACTED_MODULE.declarations) {+ declarations.push(...extractDeclarations(await download(source, commit), source, names))+ }+ texts.set(EXTRACTED_MODULE.file, declarations.join('\n\n'))+ return texts+}++/**+ * Mermaid type-checks its own code under its own settings, which are looser than ours; copies are+ * checked there, and their declarations still give their callers types here.+ */+const COPIED_HEADER = '// @ts-nocheck\n'++const root = await resolveWorkspaceRoot(import.meta.dir)++if (process.argv.includes('--check')) {+ const latest = latestRelease()+ if (latest.tag === MERMAID_RELEASE.tag) {+ console.log(`Pinned to ${MERMAID_RELEASE.tag}, Mermaid's latest release.`)+ process.exit(0)+ }+ const scratch = join(root, 'node_modules/.cache/mermaid-sources')+ const [pinned, current] = await Promise.all([+ upstream(MERMAID_RELEASE.commit),+ upstream(latest.commit)+ ])+ for (const path of FOLLOWED_SOURCES) {+ const name = path.split('/').at(-1) ?? path+ pinned.set(name, await download(path))+ current.set(name, await download(path, latest.commit))+ }+ let changed = false+ for (const [name, text] of pinned) {+ const now = current.get(name) ?? ''+ if (text === now) continue+ changed = true+ await Bun.write(join(scratch, 'pinned', name), text)+ await Bun.write(join(scratch, 'latest', name), now)+ Bun.spawnSync(+ ['git', 'diff', '--no-index', join(scratch, 'pinned', name), join(scratch, 'latest', name)],+ { stdout: 'inherit', stderr: 'inherit' }+ )+ }+ console.log(+ changed+ ? `${latest.tag} changes the sources above: pin it in sources.ts, regenerate, and follow the changes to FlowDB and the shapes in @open-pencil/mermaid.`+ : `${latest.tag} is out, with the same sources as ${MERMAID_RELEASE.tag}.`+ )+ process.exit(changed ? 1 : 0)+}++const texts = await upstream(MERMAID_RELEASE.commit)+const files = new Map<string, string>([['MERMAID-LICENSE.txt', await download('LICENSE')]])+for (const grammar of GRAMMARS) {+ const source = texts.get(`${grammar.parser}.jison`) ?? ''+ files.set(`${grammar.parser}.jison`, source)+ files.set(`${grammar.parser}.js`, parserModule(grammar, source))+}+for (const module of COPIED_MODULES) {+ const source = texts.get(module.file) ?? ''+ files.set(module.file, `${COPIED_HEADER}${provenance([module.source], 'Copied')}\n${source}`)+}+files.set(+ EXTRACTED_MODULE.file,+ [+ COPIED_HEADER ++ provenance(+ EXTRACTED_MODULE.declarations.map(({ source }) => source),+ 'Copied'+ ),+ ...EXTRACTED_MODULE.imports,+ '',+ texts.get(EXTRACTED_MODULE.file) ?? '',+ ''+ ].join('\n')+)+for (const [file, content] of files) await Bun.write(join(root, UPSTREAM_DIR, file), content)+await Bun.write(join(root, CHECKSUMS_FILE), `${JSON.stringify(checksums(files), null, 2)}\n`)+console.log(`Mermaid sources written from ${MERMAID_RELEASE.tag}`)diff --git a/tools/generate/mermaid-sources/src/jison.ts b/tools/generate/mermaid-sources/src/jison.tsnew file mode 100644index 000000000..f9218749b--- /dev/null+++ b/tools/generate/mermaid-sources/src/jison.ts@@ -0,0 +1,20 @@+import jison from 'jison'++import { provenance, type Grammar } from './sources'++/**+ * A JISON grammar as an ES module exporting its parser, built with the options Mermaid's build+ * uses (`.build/jisonTransformer.ts`), under a header naming where it came from.+ */+export function parserModule(grammar: Grammar, source: string): string {+ const generator = new jison.Generator(source, { moduleType: 'js', 'token-stack': true })+ const parser = generator.generate({ moduleMain: '() => {}' })+ return [+ '// @ts-nocheck',+ provenance([grammar.source], 'Generated'),+ parser,+ 'parser.parser = parser',+ 'export default parser',+ ''+ ].join('\n')+}diff --git a/tools/generate/mermaid-sources/src/releases.ts b/tools/generate/mermaid-sources/src/releases.tsnew file mode 100644index 000000000..70151977e--- /dev/null+++ b/tools/generate/mermaid-sources/src/releases.ts@@ -0,0 +1,48 @@+/** A `[email protected]` tag's version as numbers, or null for another package's or a pre-release. */+export function releaseVersion(tag: string): number[] | null {+ const match = /^mermaid@(\d+)\.(\d+)\.(\d+)$/.exec(tag)+ return match ? match.slice(1).map(Number) : null+}++function newer(a: number[], b: number[]): boolean {+ for (let i = 0; i < 3; i++) {+ if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0)+ }+ return false+}++/**+ * The newest `[email protected]` release in `git ls-remote --tags` output, with the commit it tags:+ * an annotated tag's `^{}` line names the commit, its own line the tag object.+ */+export function newestRelease(lsRemote: string): { tag: string; commit: string } | null {+ const commits = new Map<string, string>()+ for (const line of lsRemote.split('\n')) {+ const [sha, ref] = line.split('\t')+ if (!sha || !ref.startsWith('refs/tags/')) continue+ const name = ref.slice('refs/tags/'.length)+ if (name.endsWith('^{}')) commits.set(name.slice(0, -3), sha)+ else if (!commits.has(name)) commits.set(name, sha)+ }+ let best: { tag: string; commit: string; version: number[] } | null = null+ for (const [tag, commit] of commits) {+ const version = releaseVersion(tag)+ if (version && (!best || newer(version, best.version))) best = { tag, commit, version }+ }+ return best && { tag: best.tag, commit: best.commit }+}++/** Mermaid's latest release, from the tags in its repository. */+export function latestRelease(): { tag: string; commit: string } {+ const listed = Bun.spawnSync([+ 'git',+ 'ls-remote',+ '--tags',+ 'https://github.com/mermaid-js/mermaid',+ 'refs/tags/mermaid@*'+ ])+ if (!listed.success) throw new Error(`git ls-remote: ${listed.stderr.toString()}`)+ const latest = newestRelease(listed.stdout.toString())+ if (!latest) throw new Error('Mermaid has no [email protected] tag')+ return latest+}diff --git a/tools/generate/mermaid-sources/src/sources.ts b/tools/generate/mermaid-sources/src/sources.tsnew file mode 100644index 000000000..f9cba8368--- /dev/null+++ b/tools/generate/mermaid-sources/src/sources.ts@@ -0,0 +1,86 @@+/**+ * The Mermaid sources `@open-pencil/mermaid` runs, taken from one pinned Mermaid release and+ * committed under `packages/mermaid/src/upstream`, so building and testing never need the network.+ *+ * Mermaid parses flowcharts with a JISON grammar whose parser calls methods on a `yy` object;+ * Mermaid's `FlowDB` fills its renderer's state there, and `@open-pencil/mermaid` supplies its+ * own object that builds a typed model instead. The grammar is not in Mermaid's npm package, so+ * it is downloaded from the release's commit and built as Mermaid's build builds it. The text+ * preparation Mermaid runs before a grammar sees the text (front matter, directives, comments,+ * and `#name;` entities) is copied as Mermaid wrote it.+ *+ * When Mermaid switches flowcharts to its new parser: Mermaid is moving each diagram from JISON+ * and Langium to a Chevrotain lexer, parser, and visitor kept beside the diagram+ * (mermaid-js/mermaid#7855, pie charts first). Once flowcharts have one, copy those TypeScript+ * files here instead of `flow.jison`, add the `chevrotain` runtime to `@open-pencil/mermaid`,+ * and adapt `packages/mermaid/src/flowchart/builder.ts` to what the visitor produces; the model+ * and everything that reads it stay as they are.+ */+export const MERMAID_RELEASE = {+ tag: '[email protected]',+ commit: '1fb7869866dd619168d840291c9c54b4f129758b'+}++/** Where the copied sources, the parsers built from them, and Mermaid's licence go. */+export const UPSTREAM_DIR = 'packages/mermaid/src/upstream'++export interface Grammar {+ /** The parser's file name in the upstream folder. */+ parser: string+ /** The grammar's path in Mermaid's repository. */+ source: string+}++export const GRAMMARS: Grammar[] = [+ { parser: 'flow', source: 'packages/mermaid/src/diagrams/flowchart/parser/flow.jison' }+]++/** A Mermaid module copied whole, which works only while it imports nothing. */+export interface CopiedModule {+ file: string+ source: string+}++export const COPIED_MODULES: CopiedModule[] = [+ { file: 'regexes.ts', source: 'packages/mermaid/src/diagram-api/regexes.ts' },+ { file: 'comments.ts', source: 'packages/mermaid/src/diagram-api/comments.ts' }+]++/**+ * Declarations copied out of Mermaid modules that hold too much else to take whole, into one+ * module of their own, which imports what they use from the copied modules.+ */+export const EXTRACTED_MODULE = {+ file: 'preprocess.ts',+ imports: ["import { directiveRegex } from './regexes'"],+ declarations: [+ { source: 'packages/mermaid/src/preprocess.ts', names: ['cleanupText'] },+ {+ source: 'packages/mermaid/src/utils.ts',+ names: ['removeDirectives', 'encodeEntities', 'decodeEntities']+ }+ ]+}++/**+ * Mermaid sources `@open-pencil/mermaid` follows by hand rather than copies: what the grammar's+ * calls mean (`FlowDB`) and the shape names. `--check` shows how a newer release changes them.+ */+export const FOLLOWED_SOURCES = [+ 'packages/mermaid/src/diagrams/flowchart/flowDb.ts',+ 'packages/mermaid/src/rendering-util/rendering-elements/shapes.ts'+]++export function sourceURL(path: string, commit = MERMAID_RELEASE.commit): string {+ return `https://raw.githubusercontent.com/mermaid-js/mermaid/${commit}/${path}`+}++/** The header a copied or generated file starts with, naming where it came from. */+export function provenance(sources: string[], how: string): string {+ return [+ `// ${how} by \`bun run generate:mermaid-sources\` from ${MERMAID_RELEASE.tag}`,+ ...sources.map((source) => `// (${sourceURL(source)})`),+ '// Copyright (c) 2014 - 2022 Knut Sveidqvist. MIT License; see MERMAID-LICENSE.txt.',+ '// Do not edit: change the pinned release in tools/generate/mermaid-sources and regenerate.'+ ].join('\n')+}diff --git a/tools/generate/mermaid-sources/src/vendor.d.ts b/tools/generate/mermaid-sources/src/vendor.d.tsnew file mode 100644index 000000000..482ee1191--- /dev/null+++ b/tools/generate/mermaid-sources/src/vendor.d.ts@@ -0,0 +1,14 @@+declare module 'jison' {+ interface GeneratorOptions {+ moduleType?: 'js' | 'commonjs' | 'amd'+ 'token-stack'?: boolean+ }++ class Generator {+ constructor(grammar: string, options?: GeneratorOptions)+ generate(options?: { moduleMain?: string }): string+ }++ const jison: { Generator: typeof Generator }+ export default jison+}diff --git a/tools/generate/mermaid-sources/tests/checksums.test.ts b/tools/generate/mermaid-sources/tests/checksums.test.tsnew file mode 100644index 000000000..0b6294f01--- /dev/null+++ b/tools/generate/mermaid-sources/tests/checksums.test.ts@@ -0,0 +1,23 @@+import { expect, test } from 'bun:test'+import { join } from 'node:path'++import { checksum, CHECKSUMS_FILE } from '#mermaid-sources/checksums'+import { UPSTREAM_DIR } from '#mermaid-sources/sources'+import * as v from 'valibot'++import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts-tools'++const root = await resolveWorkspaceRoot(import.meta.dir)++test('the copied and generated Mermaid sources are as the generator wrote them', async () => {+ const recorded = v.parse(+ v.record(v.string(), v.string()),+ await Bun.file(join(root, CHECKSUMS_FILE)).json()+ )+ expect(Object.keys(recorded).length).toBeGreaterThan(0)+ for (const [file, expected] of Object.entries(recorded)) {+ const content = await Bun.file(join(root, UPSTREAM_DIR, file)).text()+ // A mismatch means the file was edited by hand: change the generator and regenerate instead.+ expect({ file, checksum: checksum(content) }).toEqual({ file, checksum: expected })+ }+})diff --git a/tools/generate/mermaid-sources/tests/extract.test.ts b/tools/generate/mermaid-sources/tests/extract.test.tsnew file mode 100644index 000000000..eb1c3627c--- /dev/null+++ b/tools/generate/mermaid-sources/tests/extract.test.ts@@ -0,0 +1,34 @@+import { expect, test } from 'bun:test'++import { extractDeclarations, hasImports } from '#mermaid-sources/extract'++const MODULE = `import { other } from './other'++/** Says hello. */+const hello = (name: string) => 'hello ' + name++export const goodbye = function (name: string): string {+ return 'goodbye ' + name+}++function helper() {}+`++test('copies declarations as written, with their comments, exported', () => {+ expect(extractDeclarations(MODULE, 'm.ts', ['hello', 'goodbye', 'helper'])).toEqual([+ "/** Says hello. */\nexport const hello = (name: string) => 'hello ' + name",+ "export const goodbye = function (name: string): string {\n return 'goodbye ' + name\n}",+ 'export function helper() {}'+ ])+})++test('fails when a release no longer declares a name, rather than copying something else', () => {+ expect(() => extractDeclarations(MODULE, 'm.ts', ['farewell'])).toThrow(+ 'm.ts no longer declares farewell'+ )+})++test('tells modules that import others from ones that can be copied whole', () => {+ expect(hasImports(MODULE, 'm.ts')).toBe(true)+ expect(hasImports('export const a = 1\n', 'a.ts')).toBe(false)+})diff --git a/tools/generate/mermaid-sources/tests/releases.test.ts b/tools/generate/mermaid-sources/tests/releases.test.tsnew file mode 100644index 000000000..a3f9673b4--- /dev/null+++ b/tools/generate/mermaid-sources/tests/releases.test.ts@@ -0,0 +1,21 @@+import { expect, test } from 'bun:test'++import { newestRelease, releaseVersion } from '#mermaid-sources/releases'++test('reads only [email protected] tags as releases', () => {+ expect(releaseVersion('[email protected]')).toEqual([12, 2, 0])+ expect(releaseVersion('@mermaid-js/[email protected]')).toBeNull()+ expect(releaseVersion('[email protected]')).toBeNull()+})++test('picks the newest release and the commit an annotated tag points at', () => {+ const lsRemote = [+ 'a1\trefs/tags/[email protected]',+ 'b1\trefs/tags/[email protected]',+ 'b2\trefs/tags/[email protected]^{}',+ 'c1\trefs/tags/[email protected]',+ 'd1\trefs/tags/[email protected]'+ ].join('\n')+ expect(newestRelease(lsRemote)).toEqual({ tag: '[email protected]', commit: 'b2' })+ expect(newestRelease('p\trefs/tags/@mermaid-js/[email protected]')).toBeNull()+})diff --git a/tsconfig.json b/tsconfig.jsonindex 70a8e4e78..78495109d 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -112,6 +112,12 @@"@open-pencil/drawio": ["./packages/drawio/src/index.ts"],+ "#mermaid/*": [+ "./packages/mermaid/src/*"+ ],+ "@open-pencil/mermaid": [+ "./packages/mermaid/src/index.ts"+ ],"#emit/*": ["./packages/emit/src/*"],diff --git a/tsconfig.tests.json b/tsconfig.tests.jsonindex 1095abc89..e85821e98 100644--- a/tsconfig.tests.json+++ b/tsconfig.tests.json@@ -106,6 +106,12 @@"@open-pencil/drawio": ["./packages/drawio/src/index.ts"],+ "#mermaid/*": [+ "./packages/mermaid/src/*"+ ],+ "@open-pencil/mermaid": [+ "./packages/mermaid/src/index.ts"+ ],"#emit/*": ["./packages/emit/src/*"],