Skip to content

Turn complex codebases into clear, navigable architecture diagrams with Claude Code.

Release/v0.1.6 validate (#14)

김승진1e50feb7efef
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index c6f044f..64b834e 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -7,7 +7,7 @@
{
"name": "oh-my-mermaid",
"description": "Turn complex codebases into clear, navigable architecture diagrams with Mermaid",
- "version": "0.1.5",
+ "version": "0.1.6",
"source": "./",
"category": "development",
"homepage": "https://github.com/oh-my-mermaid/oh-my-mermaid"
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 5bc86d5..a4a411d 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "oh-my-mermaid",
"description": "Turn complex codebases into clear, navigable architecture diagrams",
- "version": "0.1.5",
+ "version": "0.1.6",
"author": {
"name": "oh-my-mermaid"
},
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index beb0d4b..9af69d5 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -38,22 +38,7 @@ jobs:
echo "changed=false" >> "$GITHUB_OUTPUT"
fi
- - name: Skip if version unchanged
- if: steps.version.outputs.changed != 'true'
- run: echo "Version unchanged (${{ steps.version.outputs.old }}), skipping release."
-
- - name: Install, test, build, sync
- if: steps.version.outputs.changed == 'true'
- run: |
- npm ci
- npm test
- npm run build
- npm run sync-version
- npm run check-version-sync
- git diff --exit-code -- .claude-plugin/plugin.json .claude-plugin/marketplace.json package-lock.json
-
- name: Detect existing release artifacts
- if: steps.version.outputs.changed == 'true'
id: release_state
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -79,21 +64,51 @@ jobs:
echo "release_exists=false" >> "$GITHUB_OUTPUT"
fi
+ - name: Decide whether release should run
+ id: release_gate
+ env:
+ RELEASE_CURRENT_VERSION: ${{ steps.version.outputs.new }}
+ RELEASE_PREVIOUS_VERSION: ${{ steps.version.outputs.old }}
+ RELEASE_NPM_PUBLISHED: ${{ steps.release_state.outputs.npm_published }}
+ RELEASE_TAG_EXISTS: ${{ steps.release_state.outputs.tag_exists }}
+ RELEASE_GITHUB_RELEASE_EXISTS: ${{ steps.release_state.outputs.release_exists }}
+ run: |
+ DECISION=$(node scripts/release-decision.js)
+ echo "$DECISION"
+ echo "changed=$(echo "$DECISION" | node -p "JSON.parse(require('fs').readFileSync('/dev/stdin','utf8')).changed")" >> "$GITHUB_OUTPUT"
+ echo "should_release=$(echo "$DECISION" | node -p "JSON.parse(require('fs').readFileSync('/dev/stdin','utf8')).shouldRelease")" >> "$GITHUB_OUTPUT"
+ echo "reason=$(echo "$DECISION" | node -p "JSON.parse(require('fs').readFileSync('/dev/stdin','utf8')).reason")" >> "$GITHUB_OUTPUT"
+
+ - name: Skip if release artifacts are already complete
+ if: steps.release_gate.outputs.should_release != 'true'
+ run: |
+ echo "Skipping release: ${{ steps.release_gate.outputs.reason }}."
+
+ - name: Install, test, build, sync
+ if: steps.release_gate.outputs.should_release == 'true'
+ run: |
+ npm ci
+ npm test
+ npm run build
+ npm run sync-version
+ npm run check-version-sync
+ git diff --exit-code -- .claude-plugin/plugin.json .claude-plugin/marketplace.json package-lock.json
+
- name: Publish to npm
- if: steps.version.outputs.changed == 'true' && steps.release_state.outputs.npm_published != 'true'
+ if: steps.release_gate.outputs.should_release == 'true' && steps.release_state.outputs.npm_published != 'true'
run: npm publish --provenance --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Create git tag
- if: steps.version.outputs.changed == 'true' && steps.release_state.outputs.tag_exists != 'true'
+ if: steps.release_gate.outputs.should_release == 'true' && steps.release_state.outputs.tag_exists != 'true'
run: |
TAG="v${{ steps.version.outputs.new }}"
git tag "$TAG"
git push origin "$TAG"
- name: Create GitHub release
- if: steps.version.outputs.changed == 'true' && steps.release_state.outputs.release_exists != 'true'
+ if: steps.release_gate.outputs.should_release == 'true' && steps.release_state.outputs.release_exists != 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
diff --git a/package-lock.json b/package-lock.json
index 0da24e6..a46f76e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "oh-my-mermaid",
- "version": "0.1.5",
+ "version": "0.1.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "oh-my-mermaid",
- "version": "0.1.5",
+ "version": "0.1.6",
"license": "MIT",
"dependencies": {
"yaml": "^2.8.3"
diff --git a/package.json b/package.json
index dece27b..21f5fa1 100644
--- a/package.json
+++ b/package.json
@@ -1,10 +1,10 @@
{
"name": "oh-my-mermaid",
- "version": "0.1.5",
+ "version": "0.1.6",
"description": "Architecture mirror for vibe coding — CLI + Claude Code skills",
"type": "module",
"bin": {
- "omm": "./dist/cli.js"
+ "omm": "dist/cli.js"
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -14,6 +14,14 @@
".claude-plugin/",
"LICENSE"
],
+ "homepage": "https://github.com/oh-my-mermaid/oh-my-mermaid",
+ "bugs": {
+ "url": "https://github.com/oh-my-mermaid/oh-my-mermaid/issues"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/oh-my-mermaid/oh-my-mermaid.git"
+ },
"keywords": [
"mermaid",
"architecture",
diff --git a/scripts/release-decision.js b/scripts/release-decision.js
new file mode 100644
index 0000000..4ba6af7
--- /dev/null
+++ b/scripts/release-decision.js
@@ -0,0 +1,50 @@
+import { pathToFileURL } from 'node:url';
+
+function parseFlag(value) {
+ return value === true || value === 'true';
+}
+
+export function decideReleaseAction({
+ currentVersion,
+ previousVersion,
+ npmPublished,
+ tagExists,
+ releaseExists,
+}) {
+ const changed = currentVersion !== previousVersion;
+ const artifactsComplete = parseFlag(npmPublished) && parseFlag(tagExists) && parseFlag(releaseExists);
+
+ if (changed) {
+ return {
+ changed: true,
+ shouldRelease: true,
+ reason: 'version changed',
+ };
+ }
+
+ if (!artifactsComplete) {
+ return {
+ changed: false,
+ shouldRelease: true,
+ reason: 'release artifacts missing for current version',
+ };
+ }
+
+ return {
+ changed: false,
+ shouldRelease: false,
+ reason: 'version unchanged and release artifacts already exist',
+ };
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ const decision = decideReleaseAction({
+ currentVersion: process.env.RELEASE_CURRENT_VERSION ?? '',
+ previousVersion: process.env.RELEASE_PREVIOUS_VERSION ?? '',
+ npmPublished: process.env.RELEASE_NPM_PUBLISHED ?? 'false',
+ tagExists: process.env.RELEASE_TAG_EXISTS ?? 'false',
+ releaseExists: process.env.RELEASE_GITHUB_RELEASE_EXISTS ?? 'false',
+ });
+
+ process.stdout.write(JSON.stringify(decision));
+}
diff --git a/src/__tests__/release-decision.test.ts b/src/__tests__/release-decision.test.ts
new file mode 100644
index 0000000..3d25f71
--- /dev/null
+++ b/src/__tests__/release-decision.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+import { decideReleaseAction } from '../../scripts/release-decision.js';
+
+describe('decideReleaseAction', () => {
+ it('skips only when version is unchanged and all artifacts already exist', () => {
+ expect(decideReleaseAction({
+ currentVersion: '0.1.6',
+ previousVersion: '0.1.6',
+ npmPublished: true,
+ tagExists: true,
+ releaseExists: true,
+ })).toEqual({
+ changed: false,
+ shouldRelease: false,
+ reason: 'version unchanged and release artifacts already exist',
+ });
+ });
+
+ it('retries release when version is unchanged but npm publish is missing', () => {
+ expect(decideReleaseAction({
+ currentVersion: '0.1.6',
+ previousVersion: '0.1.6',
+ npmPublished: false,
+ tagExists: false,
+ releaseExists: false,
+ })).toEqual({
+ changed: false,
+ shouldRelease: true,
+ reason: 'release artifacts missing for current version',
+ });
+ });
+
+ it('releases when version changed even if no artifacts exist yet', () => {
+ expect(decideReleaseAction({
+ currentVersion: '0.1.7',
+ previousVersion: '0.1.6',
+ npmPublished: false,
+ tagExists: false,
+ releaseExists: false,
+ })).toEqual({
+ changed: true,
+ shouldRelease: true,
+ reason: 'version changed',
+ });
+ });
+
+ it('continues when some artifacts exist but others are missing', () => {
+ expect(decideReleaseAction({
+ currentVersion: '0.1.6',
+ previousVersion: '0.1.6',
+ npmPublished: true,
+ tagExists: false,
+ releaseExists: true,
+ })).toEqual({
+ changed: false,
+ shouldRelease: true,
+ reason: 'release artifacts missing for current version',
+ });
+ });
+});
diff --git a/src/__tests__/validate.test.ts b/src/__tests__/validate.test.ts
new file mode 100644
index 0000000..dfcbe67
--- /dev/null
+++ b/src/__tests__/validate.test.ts
@@ -0,0 +1,149 @@
+import { describe, it, expect } from 'vitest';
+import { validateDiagram } from '../lib/validate.js';
+
+describe('validateDiagram', () => {
+ it('passes a valid diagram with no issues', () => {
+ const diagram = [
+ 'graph LR',
+ ' client["Client\\nsrc/client/index.ts"] -->|"sends request"| api["API\\nsrc/api/"]',
+ ' api -->|"queries"| db["Database\\nsrc/db/"]',
+ ' db -->|"returns rows"| api',
+ ' api -->|"JSON response"| client',
+ ' client -->|"renders"| ui["UI\\nsrc/ui/"]',
+ ].join('\n');
+ const result = validateDiagram(diagram);
+ expect(result.valid).toBe(true);
+ expect(result.issues).toHaveLength(0);
+ });
+
+ it('errors on missing graph declaration', () => {
+ const diagram = `client["Client"] --> api["API"]`;
+ const result = validateDiagram(diagram);
+ expect(result.valid).toBe(false);
+ const issue = result.issues.find(i => i.rule === 'graph-declaration');
+ expect(issue).toBeDefined();
+ expect(issue!.level).toBe('error');
+ });
+
+ it('errors on unbalanced brackets (quote-aware)', () => {
+ const diagram = `graph LR
+ A["unclosed`;
+ const result = validateDiagram(diagram);
+ expect(result.valid).toBe(false);
+ const issue = result.issues.find(i => i.rule === 'balanced-brackets');
+ expect(issue).toBeDefined();
+ expect(issue!.level).toBe('error');
+ });
+
+ it('does not false-positive on brackets inside quotes', () => {
+ const diagram = `graph LR
+ A["Label with [brackets] inside"] -->|"some (label)"| B["Other"]`;
+ const result = validateDiagram(diagram);
+ const bracketIssue = result.issues.find(i => i.rule === 'balanced-brackets');
+ expect(bracketIssue).toBeUndefined();
+ });
+
+ it('warns on edge without label (-->, ==>, -.->)', () => {
+ const diagram = [
+ 'graph LR',
+ ' A["Svc A\\nsrc/a.ts"] --> B["Svc B\\nsrc/b.ts"]',
+ ' B ==> C["Svc C\\nsrc/c.ts"]',
+ ].join('\n');
+ const result = validateDiagram(diagram);
+ const edgeIssues = result.issues.filter(i => i.rule === 'edge-label');
+ expect(edgeIssues.length).toBe(2);
+ expect(edgeIssues[0].level).toBe('warning');
+ });
+
+ it('errors on @ref to nonexistent class', () => {
+ const diagram = `graph LR
+ A["@ghost-class"]`;
+ const result = validateDiagram(diagram, { className: 'overview', allClasses: ['overview', 'auth'] });
+ expect(result.valid).toBe(false);
+ const issue = result.issues.find(i => i.rule === 'ref-exists');
+ expect(issue).toBeDefined();
+ expect(issue!.level).toBe('error');
+ });
+
+ it('errors on self @ref', () => {
+ const diagram = `graph LR
+ A["@auth-flow"]`;
+ const result = validateDiagram(diagram, { className: 'auth-flow', allClasses: ['auth-flow', 'overview'] });
+ expect(result.valid).toBe(false);
+ const issue = result.issues.find(i => i.rule === 'ref-self');
+ expect(issue).toBeDefined();
+ expect(issue!.level).toBe('error');
+ });
+
+ it('allows general cycles (not self-ref)', () => {
+ const diagramA = `graph LR
+ X["@class-b"]`;
+ // class-a references class-b — this is fine even if class-b references class-a
+ const result = validateDiagram(diagramA, { className: 'class-a', allClasses: ['class-a', 'class-b'] });
+ const circularIssue = result.issues.find(i => i.rule === 'ref-self');
+ expect(circularIssue).toBeUndefined();
+ });
+
+ it('warns on invalid classDef name', () => {
+ const diagram = [
+ 'graph LR',
+ ' A["Svc\\nsrc/a.ts"] -->|"calls"| B["Svc\\nsrc/b.ts"]',
+ ' classDef highlight fill:#ff0,stroke:#ff0,color:#000',
+ ].join('\n');
+ const result = validateDiagram(diagram);
+ const issue = result.issues.find(i => i.rule === 'classdef-name');
+ expect(issue).toBeDefined();
+ expect(issue!.level).toBe('warning');
+ });
+
+ it('warns on wrong classDef color (checks declared attributes only)', () => {
+ const diagram = [
+ 'graph LR',
+ ' A["Svc\\nsrc/a.ts"] -->|"calls"| B["Svc\\nsrc/b.ts"]',
+ ' classDef external fill:#ffffff,stroke:#585b70,color:#cdd6f4',
+ ].join('\n');
+ const result = validateDiagram(diagram);
+ const issue = result.issues.find(i => i.rule === 'classdef-color');
+ expect(issue).toBeDefined();
+ expect(issue!.level).toBe('warning');
+ });
+
+ it('passes classDef with correct colors in any attribute order', () => {
+ const diagram = [
+ 'graph LR',
+ ' A["Svc\\nsrc/a.ts"] -->|"calls"| B["Svc\\nsrc/b.ts"]',
+ ' classDef external color:#cdd6f4,fill:#585b70,stroke:#585b70',
+ ].join('\n');
+ const result = validateDiagram(diagram);
+ const colorIssue = result.issues.find(i => i.rule === 'classdef-color');
+ expect(colorIssue).toBeUndefined();
+ });
+
+ it('warns on too many nodes', () => {
+ const nodes = Array.from({ length: 20 }, (_, i) => ` N${i}["Node ${i}\\nsrc/${i}.ts"]`).join('\n');
+ const diagram = `graph LR\n${nodes}`;
+ const result = validateDiagram(diagram);
+ const issue = result.issues.find(i => i.rule === 'node-count');
+ expect(issue).toBeDefined();
+ expect(issue!.level).toBe('warning');
+ });
+
+ it('warns on too few nodes', () => {
+ const diagram = [
+ 'graph LR',
+ ' A["Only\\nsrc/a.ts"] -->|"calls"| B["Two\\nsrc/b.ts"]',
+ ].join('\n');
+ const result = validateDiagram(diagram);
+ const issue = result.issues.find(i => i.rule === 'node-count');
+ expect(issue).toBeDefined();
+ expect(issue!.level).toBe('warning');
+ });
+
+ it('skips ref checks when no context provided', () => {
+ const diagram = `graph LR
+ A["@some-class"]`;
+ const result = validateDiagram(diagram);
+ const refIssues = result.issues.filter(i => i.rule === 'ref-exists' || i.rule === 'ref-self');
+ expect(refIssues).toHaveLength(0);
+ });
+});
diff --git a/src/cli.ts b/src/cli.ts
index 130c2a0..446098d 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -18,8 +18,9 @@ import { commandShare } from './commands/share.js';
import { commandSetup } from './commands/setup.js';
import { commandUpdate } from './commands/update.js';
import { commandOrg } from './commands/org.js';
+import { commandValidate } from './commands/validate.js';
-const GLOBAL_COMMANDS = ['init', 'setup', 'update', 'list', 'show', 'delete', 'status', 'diff', 'refs', 'view', 'login', 'logout', 'push', 'pull', 'link', 'share', 'org', 'help'];
+const GLOBAL_COMMANDS = ['init', 'setup', 'update', 'list', 'show', 'delete', 'status', 'diff', 'refs', 'validate', 'view', 'login', 'logout', 'push', 'pull', 'link', 'share', 'org', 'help'];
function printHelp(): void {
const help = `
@@ -38,6 +39,7 @@ Usage:
omm diff <class> Compare current vs previous diagram
omm refs <class> Show classes that reference this class
omm refs --reverse <class> Show classes this class references
+ omm validate [class] Validate diagram(s) for syntax and conventions
omm view [--port <port>] Start web viewer (default: 3000)
omm <class> <field> Read a field (stdout)
@@ -115,6 +117,10 @@ async function main(): Promise<void> {
commandDiff(args[1]);
return;
+ case 'validate':
+ commandValidate(args[1]);
+ return;
+
case 'refs': {
let reverse = false;
let className = args[1];
diff --git a/src/commands/validate.ts b/src/commands/validate.ts
new file mode 100644
index 0000000..48d4256
--- /dev/null
+++ b/src/commands/validate.ts
@@ -0,0 +1,52 @@
+import { ensureOmmForRead, listClasses, readField, classExists } from '../lib/store.js';
+import { validateDiagram } from '../lib/validate.js';
+
+function validateClass(className: string, allClasses: string[]): { errors: number; warnings: number } {
+ const diagram = readField(className, 'diagram');
+ if (!diagram) {
+ process.stdout.write(`${className}:\n (no diagram)\n\n`);
+ return { errors: 0, warnings: 0 };
+ }
+
+ const result = validateDiagram(diagram, { className, allClasses });
+ const errors = result.issues.filter(i => i.level === 'error').length;
+ const warnings = result.issues.filter(i => i.level === 'warning').length;
+
+ const status = result.valid
+ ? `✓ valid${warnings > 0 ? ` (${warnings} warning${warnings > 1 ? 's' : ''})` : ''}`
+ : `✗ invalid (${errors} error${errors > 1 ? 's' : ''}${warnings > 0 ? `, ${warnings} warning${warnings > 1 ? 's' : ''}` : ''})`;
+
+ process.stdout.write(`${className}:\n ${status}\n`);
+ for (const issue of result.issues) {
+ const loc = issue.line ? ` line ${issue.line}:` : '';
+ process.stdout.write(` ${issue.level} [${issue.rule}]${loc} ${issue.message}\n`);
+ }
+ process.stdout.write('\n');
+
+ return { errors, warnings };
+}
+
+export function commandValidate(className?: string): void {
+ if (!ensureOmmForRead()) return;
+
+ const allClasses = listClasses();
+
+ if (className) {
+ if (!classExists(className)) {
+ process.stderr.write(`error: class '${className}' not found\n`);
+ process.exit(1);
+ }
+ const { errors } = validateClass(className, allClasses);
+ if (errors > 0) process.exit(1);
+ return;
+ }
+
+ // Validate all classes
+ let totalErrors = 0;
+ for (const cls of allClasses) {
+ const { errors } = validateClass(cls, allClasses);
+ totalErrors += errors;
+ }
+
+ if (totalErrors > 0) process.exit(1);
+}
diff --git a/src/index.ts b/src/index.ts
index 6c95630..c0494bb 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -2,5 +2,6 @@
export { initOmm, ensureOmmForRead, ensureOmmForWrite, listClasses, readField, writeField, showClass, deleteClass, classExists } from './lib/store.js';
export { diffMermaid, parseMermaid, formatDiff } from './lib/diff.js';
export { extractRefs, getIncomingRefs, getOutgoingRefs, buildRefGraph } from './lib/refs.js';
+export { validateDiagram, VALID_CLASSDEF_NAMES, CLASSDEF_PALETTE } from './lib/validate.js';
export { VALID_FIELDS, FIELD_FILES } from './types.js';
-export type { Field, ClassMeta, ClassData, DiffResult, RefEntry, OmmConfig } from './types.js';
+export type { Field, ClassMeta, ClassData, DiffResult, RefEntry, OmmConfig, ValidationIssue, ValidationResult } from './types.js';
diff --git a/src/lib/validate.ts b/src/lib/validate.ts
new file mode 100644
index 0000000..3a49262
--- /dev/null
+++ b/src/lib/validate.ts
@@ -0,0 +1,174 @@
+import { parseMermaid } from './diff.js';
+import { extractRefs } from './refs.js';
+import type { ValidationIssue, ValidationResult } from '../types.js';
+
+// --- Source-of-truth constants ---
+
+export const VALID_CLASSDEF_NAMES = ['external', 'concern', 'entry', 'store'] as const;
+
+export const CLASSDEF_PALETTE: Record<string, Record<string, string>> = {
+ external: { fill: '#585b70', stroke: '#585b70', color: '#cdd6f4' },
+ concern: { fill: '#f38ba8', stroke: '#f38ba8', color: '#1e1e2e' },
+ entry: { fill: '#89b4fa', stroke: '#89b4fa', color: '#1e1e2e' },
+ store: { fill: '#a6e3a1', stroke: '#a6e3a1', color: '#1e1e2e' },
+};
+
+// --- Helpers ---
+
+const GRAPH_DECL = /^(graph|flowchart)\s+(LR|RL|TD|TB|BT)\s*$/i;
+const DIRECTIVE_LINE = /^(graph|flowchart|classDef|class |click |style |linkStyle|subgraph|end$|%%)/i;
+
+// Edges we check for labels in v1: -->, ==>, -.->
+const EDGE_WITH_LABEL = /(-->|==>|-\.->)\s*$/;
+const EDGE_LINE = /(-->|==>|-.->)/;
+const EDGE_HAS_LABEL = /\|.*?\|/;
+
+const CLASSDEF_LINE = /^classDef\s+(\S+)\s+(.+)$/i;
+const CLASSDEF_ATTR = /(\w+)\s*:\s*(#[0-9a-fA-F]{3,8})/g;
+
+/**
+ * Quote-aware bracket balance check on a single line.
+ * Ignores characters inside double-quoted strings.
+ */
+function checkBracketBalance(line: string): boolean {
+ const counts: Record<string, number> = { '[': 0, ']': 0, '(': 0, ')': 0, '{': 0, '}': 0 };
+ let inQuote = false;
+
+ for (const ch of line) {
+ if (ch === '"') {
+ inQuote = !inQuote;
+ continue;
+ }
+ if (inQuote) continue;
+ if (ch in counts) counts[ch]++;
+ }
+
+ return counts['['] === counts[']'] &&
+ counts['('] === counts[')'] &&
+ counts['{'] === counts['}'];
+}
+
+// --- Main validation function ---
+
+export interface ValidateContext {
+ className: string;
+ allClasses: string[];
+}
+
+export function validateDiagram(text: string, context?: ValidateContext): ValidationResult {
+ const issues: ValidationIssue[] = [];
+ const lines = text.split('\n');
+ const contentLines = lines.map(l => l.trim()).filter(l => l && !l.startsWith('%%'));
+
+ // Rule: graph-declaration
+ if (contentLines.length === 0 || !GRAPH_DECL.test(contentLines[0])) {
+ issues.push({
+ level: 'error',
+ rule: 'graph-declaration',
+ message: 'Diagram must start with a graph/flowchart direction declaration (e.g., "graph LR")',
+ line: 1,
+ });
+ }
+
+ // Line-based checks
+ for (let i = 0; i < lines.length; i++) {
+ const trimmed = lines[i].trim();
+ if (!trimmed || trimmed.startsWith('%%')) continue;
+
+ // Rule: balanced-brackets (quote-aware)
+ if (!checkBracketBalance(trimmed)) {
+ issues.push({
+ level: 'error',
+ rule: 'balanced-brackets',
+ message: `Unbalanced brackets on line: ${trimmed}`,
+ line: i + 1,
+ });
+ }
+
+ // Rule: edge-label (v1: -->, ==>, -.->)
+ if (EDGE_LINE.test(trimmed) && !DIRECTIVE_LINE.test(trimmed)) {
+ if (!EDGE_HAS_LABEL.test(trimmed)) {
+ issues.push({
+ level: 'warning',
+ rule: 'edge-label',
+ message: `Edge without label: ${trimmed}`,
+ line: i + 1,
+ });
+ }
+ }
+
+ // Rule: classdef-name and classdef-color
+ const classDefMatch = trimmed.match(CLASSDEF_LINE);
+ if (classDefMatch) {
+ const name = classDefMatch[1];
+ const attrStr = classDefMatch[2];
+
+ if (!(VALID_CLASSDEF_NAMES as readonly string[]).includes(name)) {
+ issues.push({
+ level: 'warning',
+ rule: 'classdef-name',
+ message: `Unknown classDef name "${name}". Valid: ${VALID_CLASSDEF_NAMES.join(', ')}`,
+ line: i + 1,
+ });
+ } else {
+ // Check declared attributes only — order/whitespace agnostic
+ const expected = CLASSDEF_PALETTE[name];
+ let match: RegExpExecArray | null;
+ const attrPattern = new RegExp(CLASSDEF_ATTR.source, 'g');
+ while ((match = attrPattern.exec(attrStr)) !== null) {
+ const [, attr, value] = match;
+ if (attr in expected && value.toLowerCase() !== expected[attr].toLowerCase()) {
+ issues.push({
+ level: 'warning',
+ rule: 'classdef-color',
+ message: `classDef "${name}" has ${attr}:${value}, expected ${attr}:${expected[attr]}`,
+ line: i + 1,
+ });
+ }
+ }
+ }
+ }
+ }
+
+ // Rule: ref-exists and ref-self (only when context provided)
+ if (context) {
+ const refs = extractRefs(text);
+ for (const ref of refs) {
+ if (ref === context.className) {
+ issues.push({
+ level: 'error',
+ rule: 'ref-self',
+ message: `Diagram references its own class: @${ref}`,
+ });
+ } else if (!context.allClasses.includes(ref)) {
+ issues.push({
+ level: 'error',
+ rule: 'ref-exists',
+ message: `@${ref} does not exist. Available: ${context.allClasses.join(', ')}`,
+ });
+ }
+ }
+ }
+
+ // Rule: node-count (uses parseMermaid for counting only)
+ const parsed = parseMermaid(text);
+ const nodeCount = parsed.nodes.size;
+ if (nodeCount > 0 && nodeCount < 3) {
+ issues.push({
+ level: 'warning',
+ rule: 'node-count',
+ message: `${nodeCount} nodes (recommended: 5-15). Diagram may be too simple.`,
+ });
+ } else if (nodeCount > 15) {
+ issues.push({
+ level: 'warning',
+ rule: 'node-count',
+ message: `${nodeCount} nodes (recommended: 5-15). Consider splitting into sub-diagrams.`,
+ });
+ }
+
+ return {
+ valid: issues.filter(i => i.level === 'error').length === 0,
+ issues,
+ };
+}
diff --git a/src/types.ts b/src/types.ts
index f331423..7f7c275 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -52,3 +52,15 @@ export interface RefEntry {
node_id: string;
node_label?: string;
}
+
+export interface ValidationIssue {
+ level: 'error' | 'warning';
+ rule: string;
+ message: string;
+ line?: number;
+}
+
+export interface ValidationResult {
+ valid: boolean;
+ issues: ValidationIssue[];
+}