nerdgram1337 0.0.0-stage → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1966 @@
1
+ import {
2
+ ELK_NODE_PLACEMENTS,
3
+ FLOWCHART_CURVES,
4
+ MERMAID_LAYOUTS,
5
+ MERMAID_LOOKS,
6
+ MERMAID_THEMES,
7
+ diagramConfigKey,
8
+ isMermaidEnvironmentError,
9
+ locateParseError,
10
+ matchFrontMatter,
11
+ parseDiagram
12
+ } from "./chunk-KO565WWM.js";
13
+
14
+ // server/src/mermaidSyntax.ts
15
+ import mermaid from "mermaid";
16
+
17
+ // server/src/diagramLint.ts
18
+ import { parseDocument } from "yaml";
19
+
20
+ // server/src/diagramLinks.ts
21
+ var DIAGRAM_SCHEME = /^(nerdgram|diagram):/i;
22
+ var ANY_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
23
+ function isDiagramLink(url) {
24
+ if (!url || url.startsWith("//")) return false;
25
+ if (ANY_SCHEME.test(url) && !DIAGRAM_SCHEME.test(url)) return false;
26
+ const pathPart = url.split(/[?#]/)[0] ?? "";
27
+ return DIAGRAM_SCHEME.test(url) || /\.mmd$/i.test(pathPart) || pathPart.startsWith("./") || pathPart.includes("/");
28
+ }
29
+ function parentPath(filePath) {
30
+ const parts = filePath.replace(/\\/g, "/").split("/").filter(Boolean);
31
+ parts.pop();
32
+ return parts.join("/");
33
+ }
34
+ function resolveDiagramTarget(raw, sourcePath = "") {
35
+ const trimmed = raw.trim();
36
+ if (!isDiagramLink(trimmed)) return { ok: false, reason: "not-diagram" };
37
+ let target = trimmed.replace(/\\/g, "/");
38
+ const scheme = DIAGRAM_SCHEME.exec(target);
39
+ if (scheme) target = target.slice(scheme[0].length);
40
+ const cut = target.search(/[?#]/);
41
+ if (cut >= 0) target = target.slice(0, cut);
42
+ target = target.replace(/^\/+/, "");
43
+ if (!target || target.includes("\0")) return { ok: false, reason: "invalid" };
44
+ const base = scheme ? "" : parentPath(sourcePath);
45
+ const combined = base ? `${base}/${target}` : target;
46
+ const parts = [];
47
+ for (const part of combined.split("/")) {
48
+ if (!part || part === ".") continue;
49
+ if (part === "..") {
50
+ if (parts.length === 0) return { ok: false, reason: "escape" };
51
+ parts.pop();
52
+ continue;
53
+ }
54
+ if (part.startsWith(".")) return { ok: false, reason: "invalid" };
55
+ parts.push(part);
56
+ }
57
+ const path = parts.join("/");
58
+ if (!path.toLowerCase().endsWith(".mmd")) return { ok: false, reason: "not-diagram" };
59
+ return { ok: true, path };
60
+ }
61
+ function normalizeWorkspacePath(raw) {
62
+ const trimmed = raw.trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
63
+ if (!trimmed) return "";
64
+ const parts = [];
65
+ for (const part of trimmed.split("/")) {
66
+ if (!part || part === ".") continue;
67
+ if (part === "..") {
68
+ if (parts.length === 0) return trimmed.replace(/^\.\//, "");
69
+ parts.pop();
70
+ continue;
71
+ }
72
+ parts.push(part);
73
+ }
74
+ return parts.join("/");
75
+ }
76
+ function diagramTargetExists(target, paths, sourcePath = "") {
77
+ const resolved = resolveDiagramTarget(target, sourcePath);
78
+ if (!resolved.ok) return false;
79
+ return paths.some((path) => normalizeWorkspacePath(path) === resolved.path);
80
+ }
81
+ function parseClickLine(line, lineStart, lineNo) {
82
+ const match = /^\s*click\s+([A-Za-z_][\w-]*)\s+(.*)$/i.exec(line);
83
+ if (!match || match[1] == null || match[2] == null) return null;
84
+ const nodeId = match[1];
85
+ const rest = match[2];
86
+ if (/^\s*call\b/i.test(rest)) return null;
87
+ const href = /^\s*href\s+/i.exec(rest);
88
+ const urlPart = href ? rest.slice(href[0].length) : rest;
89
+ const urlPartStart = line.length - rest.length + (href ? href[0].length : 0);
90
+ const quoted = /"([^"]*)"/.exec(urlPart);
91
+ if (!quoted || quoted[1] == null || quoted.index == null) return null;
92
+ const quoteAt = urlPartStart + quoted.index;
93
+ const from = lineStart + quoteAt + 1;
94
+ return {
95
+ nodeId,
96
+ target: quoted[1],
97
+ from,
98
+ to: from + quoted[1].length,
99
+ line: lineNo,
100
+ column: quoteAt + 2
101
+ };
102
+ }
103
+
104
+ // server/src/diagramLint.ts
105
+ var LINT_RULES = [
106
+ {
107
+ id: "duplicate-id",
108
+ label: "Duplicate ids",
109
+ description: "The same id is defined again with a different label."
110
+ },
111
+ {
112
+ id: "unconnected-node",
113
+ label: "Unconnected nodes",
114
+ description: "A flowchart node is defined but never used in a connection."
115
+ },
116
+ {
117
+ id: "unlabeled-endpoint",
118
+ label: "Unlabeled endpoints",
119
+ description: "A connection names a node that was never given a label, which is usually a typo."
120
+ },
121
+ {
122
+ id: "unused-class",
123
+ label: "Unused classes",
124
+ description: "A classDef is never applied with class or :::"
125
+ },
126
+ {
127
+ id: "undefined-class",
128
+ label: "Undefined classes",
129
+ description: "A class or ::: name has no classDef."
130
+ },
131
+ {
132
+ id: "front-matter",
133
+ label: "Front matter",
134
+ description: "The YAML header is invalid, or a theme, look, layout, curve, or tag is not one Mermaid accepts."
135
+ },
136
+ {
137
+ id: "broken-click",
138
+ label: "Broken diagram links",
139
+ description: "A click link points at a workspace diagram (nerdgram:, diagram:, or a relative .mmd path) that is not in the workspace."
140
+ },
141
+ {
142
+ id: "duplicate-class",
143
+ label: "Duplicate classes",
144
+ description: "The same class name is defined again with a different label."
145
+ },
146
+ {
147
+ id: "undeclared-class",
148
+ label: "Undeclared classes",
149
+ description: "A class diagram relationship names a class that was never declared. A diagram that only uses relationships is left alone."
150
+ },
151
+ {
152
+ id: "duplicate-attribute",
153
+ label: "Duplicate attributes",
154
+ description: "An entity lists the same attribute more than once."
155
+ },
156
+ {
157
+ id: "undeclared-entity",
158
+ label: "Undeclared entities",
159
+ description: "An ER relationship names an entity that was never declared. A diagram that only uses relationships is left alone."
160
+ },
161
+ {
162
+ id: "missing-dependency",
163
+ label: "Missing task ids",
164
+ description: "A Gantt task depends on an id that no task defines."
165
+ },
166
+ {
167
+ id: "invalid-date",
168
+ label: "Invalid dates",
169
+ description: "A Gantt date does not match the diagram dateFormat, or is not a real calendar date."
170
+ },
171
+ {
172
+ id: "duplicate-sibling",
173
+ label: "Duplicate siblings",
174
+ description: "A mindmap repeats a label under the same parent, or a timeline repeats an event in one period."
175
+ },
176
+ {
177
+ id: "empty-node",
178
+ label: "Empty nodes",
179
+ description: "A mindmap node or a timeline event has no text."
180
+ }
181
+ ];
182
+ var LINT_RULE_IDS = LINT_RULES.map((rule) => rule.id);
183
+ var ID = "[A-Za-z_][\\w-]*";
184
+ var SIMPLE_ARROWS = ["<-->", "o--o", "x--x", "<--", "-->", "---", "-.->", "-.-", "==>", "===", "--o", "--x", "~~~"];
185
+ function normalizeLintRules(value) {
186
+ const out = Object.fromEntries(LINT_RULE_IDS.map((id) => [id, true]));
187
+ if (!value || typeof value !== "object" || Array.isArray(value)) return out;
188
+ const record = value;
189
+ for (const id of LINT_RULE_IDS) {
190
+ if (typeof record[id] === "boolean") out[id] = record[id];
191
+ }
192
+ return out;
193
+ }
194
+ function lintDiagram(source, options = {}) {
195
+ const enabled = normalizeLintRules(options.rules);
196
+ const diagnostics = [];
197
+ if (enabled["front-matter"]) diagnostics.push(...lintFrontMatter(source));
198
+ const model = scanDiagram(source);
199
+ if (enabled["duplicate-id"]) diagnostics.push(...duplicateIds(model));
200
+ if (enabled["unconnected-node"] && model.kind === "flowchart") diagnostics.push(...unconnectedNodes(model));
201
+ if (enabled["unlabeled-endpoint"]) diagnostics.push(...unlabeledEndpoints(model));
202
+ if (enabled["unused-class"]) diagnostics.push(...unusedClasses(model));
203
+ if (enabled["undefined-class"]) diagnostics.push(...undefinedClasses(source, model));
204
+ if (enabled["broken-click"] && options.diagramPaths) {
205
+ diagnostics.push(...brokenClicks(model, options.diagramPaths, options.sourcePath ?? ""));
206
+ }
207
+ if (model.kind === "class" && (enabled["duplicate-class"] || enabled["undeclared-class"])) {
208
+ const classDiagram = scanClassDiagram(source);
209
+ if (enabled["duplicate-class"]) diagnostics.push(...duplicateClasses(classDiagram));
210
+ if (enabled["undeclared-class"]) diagnostics.push(...undeclaredClasses(classDiagram));
211
+ }
212
+ if (model.kind === "er" && (enabled["duplicate-attribute"] || enabled["undeclared-entity"])) {
213
+ const erDiagram = scanErDiagram(source);
214
+ if (enabled["duplicate-attribute"]) diagnostics.push(...duplicateAttributes(erDiagram));
215
+ if (enabled["undeclared-entity"]) diagnostics.push(...undeclaredEntities(erDiagram));
216
+ }
217
+ if (model.kind === "gantt" && (enabled["missing-dependency"] || enabled["invalid-date"])) {
218
+ const gantt = scanGantt(source);
219
+ if (enabled["missing-dependency"]) diagnostics.push(...gantt.dependencies);
220
+ if (enabled["invalid-date"]) diagnostics.push(...gantt.dates);
221
+ }
222
+ if ((model.kind === "mindmap" || model.kind === "timeline") && (enabled["duplicate-sibling"] || enabled["empty-node"])) {
223
+ const outline = model.kind === "mindmap" ? scanMindmap(source) : scanTimeline(source);
224
+ if (enabled["duplicate-sibling"]) diagnostics.push(...outline.duplicates);
225
+ if (enabled["empty-node"]) diagnostics.push(...outline.empties);
226
+ }
227
+ diagnostics.sort((a, b) => a.from - b.from || a.line - b.line || a.ruleId.localeCompare(b.ruleId));
228
+ return diagnostics;
229
+ }
230
+ function scanDiagram(source) {
231
+ const parsed = parseDiagram(source);
232
+ const start = bodyStart(source);
233
+ const kind = diagramKind(parsed.body);
234
+ const model = { kind, nodes: [], edges: [], classDefs: [], classUses: [], clicks: [] };
235
+ eachLine(source, start, start + parsed.body.length, (line, lineStart, lineNo) => {
236
+ if (!line.trim() || line.trimStart().startsWith("%%")) return;
237
+ if (readClassDef(line, lineStart, lineNo, source, model)) return;
238
+ if (readClassStatement(line, lineStart, lineNo, model)) return;
239
+ if (readClick(line, lineStart, lineNo, model)) return;
240
+ collectInlineClasses(line, lineStart, lineNo, model);
241
+ if (kind === "flowchart") scanFlowchartLine(line, lineStart, lineNo, model);
242
+ else if (kind === "sequence") scanSequenceLine(line, lineStart, lineNo, model);
243
+ else if (kind === "state") scanStateLine(line, lineStart, lineNo, model);
244
+ });
245
+ return model;
246
+ }
247
+ function diagramKind(body) {
248
+ const key = diagramConfigKey(body);
249
+ if (key === "flowchart") return "flowchart";
250
+ if (key === "sequence") return "sequence";
251
+ if (key === "state") return "state";
252
+ if (key === "class") return "class";
253
+ if (key === "er") return "er";
254
+ if (key === "gantt") return "gantt";
255
+ if (key === "mindmap") return "mindmap";
256
+ if (key === "timeline") return "timeline";
257
+ return "other";
258
+ }
259
+ function duplicateIds(model) {
260
+ const byId = /* @__PURE__ */ new Map();
261
+ for (const node of model.nodes) {
262
+ if (!node.defined || node.label == null) continue;
263
+ const list = byId.get(node.id) ?? [];
264
+ list.push(node);
265
+ byId.set(node.id, list);
266
+ }
267
+ const used = new Set(model.nodes.map((node) => node.id));
268
+ const diagnostics = [];
269
+ for (const [id, hits] of byId) {
270
+ const first = hits[0];
271
+ if (!first) continue;
272
+ const firstLabel = first.label?.trim() ?? "";
273
+ for (const hit of hits.slice(1)) {
274
+ const label = hit.label?.trim() ?? "";
275
+ if (label === firstLabel) continue;
276
+ const nextId = freshId(id, used);
277
+ used.add(nextId);
278
+ diagnostics.push({
279
+ ruleId: "duplicate-id",
280
+ severity: "warning",
281
+ subject: id,
282
+ message: `Node "${id}" is defined again with a different label ("${label || "empty"}"). The first label is "${firstLabel || "empty"}".`,
283
+ from: hit.from,
284
+ to: hit.to,
285
+ line: hit.line,
286
+ column: hit.column,
287
+ fixes: [
288
+ {
289
+ id: "rename-duplicate",
290
+ title: `Rename to ${nextId}`,
291
+ edits: [{ from: hit.from, to: hit.to, insert: nextId }]
292
+ },
293
+ {
294
+ id: "jump-to-definition",
295
+ title: "Jump to definition",
296
+ edits: [],
297
+ jump: { from: first.from, to: first.to }
298
+ }
299
+ ]
300
+ });
301
+ }
302
+ }
303
+ return diagnostics;
304
+ }
305
+ function unconnectedNodes(model) {
306
+ const linked = /* @__PURE__ */ new Set();
307
+ for (const edge of model.edges) {
308
+ linked.add(edge.fromId);
309
+ linked.add(edge.toId);
310
+ }
311
+ const defined = /* @__PURE__ */ new Map();
312
+ for (const node of model.nodes) {
313
+ if (node.defined && !defined.has(node.id)) defined.set(node.id, node);
314
+ }
315
+ if (model.edges.length === 0 && defined.size < 2) return [];
316
+ const diagnostics = [];
317
+ for (const [id, node] of defined) {
318
+ if (linked.has(id)) continue;
319
+ diagnostics.push(unconnectedDiagnostic(id, node));
320
+ }
321
+ return diagnostics;
322
+ }
323
+ function unconnectedDiagnostic(id, at) {
324
+ return {
325
+ ruleId: "unconnected-node",
326
+ severity: "warning",
327
+ subject: id,
328
+ message: `Node "${id}" is defined but never connected to another node.`,
329
+ from: at.from,
330
+ to: at.to,
331
+ line: at.line,
332
+ column: at.column,
333
+ fixes: []
334
+ };
335
+ }
336
+ function unlabeledEndpoints(model) {
337
+ const labels = /* @__PURE__ */ new Map();
338
+ for (const node of model.nodes) {
339
+ if (!node.defined || node.label == null) continue;
340
+ const text = node.label.trim();
341
+ if (!text) continue;
342
+ if (!labels.has(node.id)) labels.set(node.id, text);
343
+ }
344
+ if (labels.size === 0 && model.kind === "flowchart") return [];
345
+ if (model.kind === "sequence" || model.kind === "state") {
346
+ const declared = model.nodes.some((node) => node.defined);
347
+ if (!declared) return [];
348
+ }
349
+ const candidates = [];
350
+ const seen = /* @__PURE__ */ new Set();
351
+ for (const edge of model.edges) {
352
+ for (const endpoint of [edge.fromSpan, edge.toSpan]) {
353
+ if (labels.has(endpoint.id) || seen.has(endpoint.id)) continue;
354
+ if (model.kind !== "flowchart" && model.nodes.some((node) => node.defined && node.id === endpoint.id)) continue;
355
+ seen.add(endpoint.id);
356
+ candidates.push(endpoint);
357
+ }
358
+ }
359
+ if (model.kind === "flowchart") {
360
+ const labeledEndpoints = /* @__PURE__ */ new Set();
361
+ for (const edge of model.edges) {
362
+ if (labels.has(edge.fromId)) labeledEndpoints.add(edge.fromId);
363
+ if (labels.has(edge.toId)) labeledEndpoints.add(edge.toId);
364
+ }
365
+ if (candidates.length > labeledEndpoints.size) return [];
366
+ }
367
+ return candidates.map((endpoint) => ({
368
+ ruleId: "unlabeled-endpoint",
369
+ severity: "warning",
370
+ subject: endpoint.id,
371
+ message: `This connection uses "${endpoint.id}", which has no label. That is often a typo.`,
372
+ from: endpoint.from,
373
+ to: endpoint.to,
374
+ line: endpoint.line,
375
+ column: endpoint.column,
376
+ fixes: []
377
+ }));
378
+ }
379
+ function unusedClasses(model) {
380
+ const used = new Set(model.classUses.map((use) => use.name));
381
+ const diagnostics = [];
382
+ const reported = /* @__PURE__ */ new Set();
383
+ for (const def of model.classDefs) {
384
+ if (def.name === "default" || used.has(def.name) || reported.has(`${def.from}:${def.name}`)) continue;
385
+ reported.add(`${def.from}:${def.name}`);
386
+ const siblings = model.classDefs.filter(
387
+ (item) => item.statementFrom === def.statementFrom && item.statementTo === def.statementTo
388
+ );
389
+ const allUnused = siblings.every((item) => item.name === "default" || !used.has(item.name));
390
+ const edits = allUnused ? [{ from: def.statementFrom, to: def.statementTo, insert: "" }] : [{ from: def.from, to: def.to, insert: "" }];
391
+ diagnostics.push({
392
+ ruleId: "unused-class",
393
+ severity: "warning",
394
+ subject: def.name,
395
+ message: `Class "${def.name}" is defined but never used.`,
396
+ from: def.from,
397
+ to: def.to,
398
+ line: def.line,
399
+ column: def.column,
400
+ fixes: [{ id: "remove-classdef", title: "Remove unused class", edits }]
401
+ });
402
+ }
403
+ return diagnostics;
404
+ }
405
+ function undefinedClasses(source, model) {
406
+ const defined = new Set(model.classDefs.map((def) => def.name));
407
+ const diagnostics = [];
408
+ const seen = /* @__PURE__ */ new Set();
409
+ for (const use of model.classUses) {
410
+ if (defined.has(use.name) || seen.has(`${use.from}:${use.name}`)) continue;
411
+ seen.add(`${use.from}:${use.name}`);
412
+ const indent = lineIndent(source, use.lineStart);
413
+ diagnostics.push({
414
+ ruleId: "undefined-class",
415
+ severity: "warning",
416
+ subject: use.name,
417
+ message: `Class "${use.name}" is used here but has no classDef.`,
418
+ from: use.from,
419
+ to: use.to,
420
+ line: use.line,
421
+ column: use.column,
422
+ fixes: [
423
+ {
424
+ id: "create-class",
425
+ title: `Create class ${use.name}`,
426
+ edits: [
427
+ {
428
+ from: use.lineStart,
429
+ to: use.lineStart,
430
+ insert: `${indent}classDef ${use.name} fill:#f9f,stroke:#333
431
+ `
432
+ }
433
+ ]
434
+ }
435
+ ]
436
+ });
437
+ }
438
+ return diagnostics;
439
+ }
440
+ function brokenClicks(model, paths, sourcePath) {
441
+ const diagnostics = [];
442
+ for (const click of model.clicks) {
443
+ if (diagramTargetExists(click.target, paths, sourcePath)) continue;
444
+ const resolved = resolveDiagramTarget(click.target, sourcePath);
445
+ const message = resolved.ok === false && resolved.reason === "escape" ? `The click link "${click.target}" leaves the workspace and does not match a diagram.` : `The click link "${click.target}" does not match a diagram in this workspace.`;
446
+ const fixes = [];
447
+ if (resolved.ok) {
448
+ fixes.push({ id: "repair-links", title: "Repair links", edits: [] });
449
+ }
450
+ diagnostics.push({
451
+ ruleId: "broken-click",
452
+ severity: "warning",
453
+ subject: click.target,
454
+ message,
455
+ from: click.from,
456
+ to: click.to,
457
+ line: click.line,
458
+ column: click.column,
459
+ fixes
460
+ });
461
+ }
462
+ return diagnostics;
463
+ }
464
+ function lintFrontMatter(source) {
465
+ const parsed = parseDiagram(source);
466
+ const diagnostics = [];
467
+ if (parsed.malformed) {
468
+ const line = parsed.errorLine ?? 1;
469
+ const span = lineSpan(source, line);
470
+ const detail = parsed.error ? ` ${parsed.error}` : "";
471
+ diagnostics.push({
472
+ ruleId: "front-matter",
473
+ severity: "error",
474
+ message: `The YAML header could not be parsed.${detail}`,
475
+ ...span,
476
+ fixes: []
477
+ });
478
+ }
479
+ if (parsed.initError) {
480
+ const at = indexOfToken(source, "%%{init") ?? indexOfToken(source, "%%{initialize") ?? lineSpan(source, 1);
481
+ diagnostics.push({
482
+ ruleId: "front-matter",
483
+ severity: "warning",
484
+ message: `The %%{init}%% directive could not be read. ${parsed.initError}`,
485
+ ...at,
486
+ fixes: []
487
+ });
488
+ }
489
+ if (parsed.malformed || !parsed.hasFrontMatter) return diagnostics;
490
+ const headerEnd = bodyStart(source);
491
+ const header = source.slice(0, headerEnd);
492
+ const known = new Set(MERMAID_THEMES);
493
+ if (parsed.theme && !known.has(parsed.theme)) {
494
+ diagnostics.push(fieldWarning(header, "theme", parsed.theme, `Theme "${parsed.theme}" is not a Mermaid theme.`));
495
+ }
496
+ if (parsed.look && !MERMAID_LOOKS.includes(parsed.look)) {
497
+ diagnostics.push(fieldWarning(header, "look", parsed.look, `Look "${parsed.look}" is not classic, handDrawn, or neo.`));
498
+ }
499
+ if (parsed.layout && !MERMAID_LAYOUTS.includes(parsed.layout)) {
500
+ diagnostics.push(fieldWarning(header, "layout", parsed.layout, `Layout "${parsed.layout}" is not dagre or elk.`));
501
+ }
502
+ if (parsed.flowchartCurve && !FLOWCHART_CURVES.includes(parsed.flowchartCurve)) {
503
+ diagnostics.push(
504
+ fieldWarning(header, "curve", parsed.flowchartCurve, `Curve "${parsed.flowchartCurve}" is not a Mermaid flowchart curve.`)
505
+ );
506
+ }
507
+ const placement = parsed.elk.nodePlacementStrategy;
508
+ if (typeof placement === "string" && !ELK_NODE_PLACEMENTS.includes(placement)) {
509
+ diagnostics.push(
510
+ fieldWarning(
511
+ header,
512
+ "nodePlacementStrategy",
513
+ placement,
514
+ `ELK node placement "${placement}" is not one of the supported strategies.`
515
+ )
516
+ );
517
+ }
518
+ const match = matchFrontMatter(source.charCodeAt(0) === 65279 ? source.slice(1) : source);
519
+ if (!match) return diagnostics;
520
+ const doc = parseDocument(match.body, { schema: "core", prettyErrors: false });
521
+ if (doc.errors.length > 0) return diagnostics;
522
+ const raw = doc.toJS();
523
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return diagnostics;
524
+ const data = raw;
525
+ if (data.title != null && (typeof data.title === "object" || Array.isArray(data.title))) {
526
+ diagnostics.push(fieldWarning(header, "title", "", "The title has to be text."));
527
+ }
528
+ const nerdgram = data.nerdgram;
529
+ if (nerdgram && typeof nerdgram === "object" && !Array.isArray(nerdgram)) {
530
+ const block = nerdgram;
531
+ if ("tags" in block && !Array.isArray(block.tags)) {
532
+ diagnostics.push(fieldWarning(header, "tags", "", "Tags have to be a list of names."));
533
+ }
534
+ if (block.description != null && typeof block.description === "object") {
535
+ diagnostics.push(fieldWarning(header, "description", "", "The description has to be text."));
536
+ }
537
+ }
538
+ return diagnostics;
539
+ }
540
+ function fieldWarning(header, key, value, message) {
541
+ const found = findField(header, key, value) ?? lineSpan(header, 1);
542
+ return {
543
+ ruleId: "front-matter",
544
+ severity: "warning",
545
+ message,
546
+ ...found,
547
+ fixes: []
548
+ };
549
+ }
550
+ function findField(header, key, value) {
551
+ let start = 0;
552
+ let lineNo = 1;
553
+ for (const line of header.split(/\n/)) {
554
+ const text = line.endsWith("\r") ? line.slice(0, -1) : line;
555
+ const pattern = new RegExp(`^\\s*${escapeRegExp(key)}\\s*:`);
556
+ if (pattern.test(text) && (value === "" || text.includes(value))) {
557
+ const valueAt = value ? text.indexOf(value) : text.indexOf(":") + 1;
558
+ const from = start + Math.max(0, valueAt);
559
+ const to = value ? from + value.length : start + text.length;
560
+ return pointSpan(header, from, Math.max(to, from + 1));
561
+ }
562
+ start += line.length + 1;
563
+ lineNo += 1;
564
+ if (lineNo > 1e4) break;
565
+ }
566
+ return null;
567
+ }
568
+ function readClassDef(line, lineStart, lineNo, source, model) {
569
+ const match = new RegExp(`^(\\s*)classDef\\s+(${ID}(?:\\s*,\\s*${ID})*)\\b`, "i").exec(line);
570
+ if (!match || match[1] == null || match[2] == null) return false;
571
+ const names = match[2].split(/\s*,\s*/);
572
+ const statement = lineStatementSpan(source, lineStart, line.length);
573
+ let cursor = match[1].length + "classDef".length;
574
+ for (const name of names) {
575
+ const at = line.indexOf(name, cursor);
576
+ if (at < 0) continue;
577
+ const from = lineStart + at;
578
+ model.classDefs.push({
579
+ name,
580
+ from,
581
+ to: from + name.length,
582
+ line: lineNo,
583
+ column: at + 1,
584
+ statementFrom: statement.from,
585
+ statementTo: statement.to
586
+ });
587
+ cursor = at + name.length;
588
+ }
589
+ return true;
590
+ }
591
+ function readClassStatement(line, lineStart, lineNo, model) {
592
+ const match = new RegExp(`^\\s*class\\s+${ID}(?:\\s*,\\s*${ID})*\\s+(${ID})\\s*;?\\s*$`, "i").exec(line);
593
+ if (!match || match[1] == null) return false;
594
+ const name = match[1];
595
+ const at = line.lastIndexOf(name);
596
+ if (at < 0) return false;
597
+ const from = lineStart + at;
598
+ model.classUses.push({
599
+ name,
600
+ from,
601
+ to: from + name.length,
602
+ line: lineNo,
603
+ column: at + 1,
604
+ lineStart
605
+ });
606
+ return true;
607
+ }
608
+ function readClick(line, lineStart, lineNo, model) {
609
+ if (!/^\s*click\b/i.test(line)) return false;
610
+ const click = parseClickLine(line, lineStart, lineNo);
611
+ const target = click?.target.trim() ?? "";
612
+ if (click && target && isDiagramLink(target)) {
613
+ model.clicks.push({
614
+ target,
615
+ from: click.from,
616
+ to: click.to,
617
+ line: click.line,
618
+ column: click.column
619
+ });
620
+ }
621
+ return true;
622
+ }
623
+ function collectInlineClasses(line, lineStart, lineNo, model) {
624
+ const pattern = /:::([A-Za-z_][\w-]*)/g;
625
+ for (const match of line.matchAll(pattern)) {
626
+ const name = match[1];
627
+ if (!name || match.index == null) continue;
628
+ const from = lineStart + match.index + 3;
629
+ model.classUses.push({
630
+ name,
631
+ from,
632
+ to: from + name.length,
633
+ line: lineNo,
634
+ column: match.index + 4,
635
+ lineStart
636
+ });
637
+ }
638
+ }
639
+ function scanFlowchartLine(line, lineStart, lineNo, model) {
640
+ const trimmed = line.trim();
641
+ if (/^(?:flowchart(?:-elk)?|graph|direction|style|linkStyle|subgraph|end)\b/i.test(trimmed)) return;
642
+ for (const statement of splitStatements(line)) {
643
+ const absolute = lineStart + statement.offset;
644
+ const pieces = splitArrows(statement.text);
645
+ if (pieces.length === 1 && pieces[0] && !pieces[0].arrow) {
646
+ for (const node of readNodes(pieces[0].text, absolute + pieces[0].offset, lineNo, true)) model.nodes.push(node);
647
+ continue;
648
+ }
649
+ const groups = pieces.map((piece) => readNodes(piece.text, absolute + piece.offset, lineNo, false));
650
+ for (const group of groups) model.nodes.push(...group);
651
+ for (let index = 0; index < groups.length - 1; index += 1) {
652
+ const left = groups[index] ?? [];
653
+ const right = groups[index + 1] ?? [];
654
+ for (const from of left) {
655
+ for (const to of right) {
656
+ model.edges.push({ fromId: from.id, toId: to.id, fromSpan: from, toSpan: to });
657
+ }
658
+ }
659
+ }
660
+ }
661
+ }
662
+ function scanSequenceLine(line, lineStart, lineNo, model) {
663
+ const declared = /^\s*(?:participant|actor)\s+(\S+?)(?:\s+as\s+(.+?))?\s*$/i.exec(line);
664
+ if (declared && declared[1]) {
665
+ const id = declared[1];
666
+ const at = line.indexOf(id);
667
+ const from = lineStart + Math.max(0, at);
668
+ const alias = declared[2]?.trim();
669
+ model.nodes.push({
670
+ id,
671
+ label: alias && alias.length > 0 ? alias : id,
672
+ defined: true,
673
+ from,
674
+ to: from + id.length,
675
+ line: lineNo,
676
+ column: Math.max(1, at + 1)
677
+ });
678
+ return;
679
+ }
680
+ const message = /^\s*(\S+?)\s*(--?(?:>>|[>x)]))[+-]?\s*(\S+?)\s*:/.exec(line);
681
+ if (!message || !message[1] || !message[3]) return;
682
+ const fromNode = sequenceEndpoint(line, lineStart, lineNo, message[1]);
683
+ const toNode = sequenceEndpoint(line, lineStart, lineNo, message[3], message[1]);
684
+ if (!fromNode || !toNode) return;
685
+ model.nodes.push(fromNode, toNode);
686
+ model.edges.push({ fromId: fromNode.id, toId: toNode.id, fromSpan: fromNode, toSpan: toNode });
687
+ }
688
+ function sequenceEndpoint(line, lineStart, lineNo, id, skip) {
689
+ const fromIndex = skip ? line.indexOf(skip) + skip.length : 0;
690
+ const at = line.indexOf(id, fromIndex);
691
+ if (at < 0) return null;
692
+ const from = lineStart + at;
693
+ return {
694
+ id,
695
+ label: null,
696
+ defined: false,
697
+ from,
698
+ to: from + id.length,
699
+ line: lineNo,
700
+ column: at + 1
701
+ };
702
+ }
703
+ function scanStateLine(line, lineStart, lineNo, model) {
704
+ if (/^\s*stateDiagram(?:-v2)?\b/i.test(line)) return;
705
+ const named = /^\s*state\s+"([^"]*)"\s+as\s+([A-Za-z_][\w-]*)/i.exec(line);
706
+ if (named && named[2]) {
707
+ const id = named[2];
708
+ const at = line.lastIndexOf(id);
709
+ const from = lineStart + at;
710
+ model.nodes.push({
711
+ id,
712
+ label: named[1]?.trim() ?? "",
713
+ defined: true,
714
+ from,
715
+ to: from + id.length,
716
+ line: lineNo,
717
+ column: at + 1
718
+ });
719
+ } else {
720
+ const bare = /^\s*state\s+([A-Za-z_][\w-]*)\b/i.exec(line);
721
+ if (bare && bare[1]) {
722
+ const id = bare[1];
723
+ const at = line.indexOf(id);
724
+ const from = lineStart + at;
725
+ model.nodes.push({
726
+ id,
727
+ label: id,
728
+ defined: true,
729
+ from,
730
+ to: from + id.length,
731
+ line: lineNo,
732
+ column: at + 1
733
+ });
734
+ }
735
+ }
736
+ const transition = /^\s*(\[\*\]|[A-Za-z_][\w-]*)\s*-->\s*(\[\*\]|[A-Za-z_][\w-]*)/.exec(line);
737
+ if (!transition || !transition[1] || !transition[2]) return;
738
+ const ends = [transition[1], transition[2]].filter((id) => id !== "[*]").map((id) => stateEndpoint(line, lineStart, lineNo, id)).filter((node) => node != null);
739
+ for (const node of ends) model.nodes.push(node);
740
+ if (ends.length === 2 && ends[0] && ends[1]) {
741
+ model.edges.push({ fromId: ends[0].id, toId: ends[1].id, fromSpan: ends[0], toSpan: ends[1] });
742
+ }
743
+ }
744
+ function stateEndpoint(line, lineStart, lineNo, id) {
745
+ const at = line.indexOf(id);
746
+ if (at < 0) return null;
747
+ const from = lineStart + at;
748
+ return { id, label: null, defined: false, from, to: from + id.length, line: lineNo, column: at + 1 };
749
+ }
750
+ function splitStatements(line) {
751
+ const parts = [];
752
+ let start = 0;
753
+ let depth = 0;
754
+ let quote = null;
755
+ for (let index = 0; index < line.length; index += 1) {
756
+ const char = line[index] ?? "";
757
+ if (quote) {
758
+ if (char === quote && line[index - 1] !== "\\") quote = null;
759
+ continue;
760
+ }
761
+ if (char === '"' || char === "'") {
762
+ quote = char;
763
+ continue;
764
+ }
765
+ if (char === "[" || char === "(" || char === "{") depth += 1;
766
+ else if (char === "]" || char === ")" || char === "}") depth = Math.max(0, depth - 1);
767
+ else if (char === ";" && depth === 0) {
768
+ parts.push({ text: line.slice(start, index), offset: start });
769
+ start = index + 1;
770
+ }
771
+ }
772
+ parts.push({ text: line.slice(start), offset: start });
773
+ return parts.filter((part) => part.text.trim().length > 0);
774
+ }
775
+ function splitArrows(text) {
776
+ const pieces = [];
777
+ let start = 0;
778
+ let depth = 0;
779
+ let quote = null;
780
+ for (let index = 0; index < text.length; index += 1) {
781
+ const char = text[index] ?? "";
782
+ if (quote) {
783
+ if (char === quote && text[index - 1] !== "\\") quote = null;
784
+ continue;
785
+ }
786
+ if (char === '"' || char === "'") {
787
+ quote = char;
788
+ continue;
789
+ }
790
+ if (char === "[" || char === "(" || char === "{") {
791
+ depth += 1;
792
+ continue;
793
+ }
794
+ if (char === "]" || char === ")" || char === "}") {
795
+ depth = Math.max(0, depth - 1);
796
+ continue;
797
+ }
798
+ if (depth !== 0) continue;
799
+ const length = matchArrow(text, index);
800
+ if (!length) continue;
801
+ pieces.push({ text: text.slice(start, index), offset: start, arrow: false });
802
+ start = index + length;
803
+ index += length - 1;
804
+ }
805
+ pieces.push({ text: text.slice(start), offset: start, arrow: false });
806
+ return pieces;
807
+ }
808
+ function matchArrow(text, index) {
809
+ if (text.startsWith("--", index) && /\s/.test(text[index + 2] ?? "") && !text.startsWith("---", index)) {
810
+ for (let cursor = index + 2; cursor < text.length; cursor += 1) {
811
+ if (text.startsWith("-->", cursor) || text.startsWith("---", cursor)) return cursor + 3 - index;
812
+ }
813
+ }
814
+ for (const arrow of SIMPLE_ARROWS) {
815
+ if (!text.startsWith(arrow, index)) continue;
816
+ let length = arrow.length;
817
+ if (text[index + length] === "|") {
818
+ const close = text.indexOf("|", index + length + 1);
819
+ if (close !== -1) length = close + 1 - index;
820
+ }
821
+ return length;
822
+ }
823
+ return 0;
824
+ }
825
+ function readNodes(text, base, lineNo, defined) {
826
+ const nodes = [];
827
+ let depth = 0;
828
+ let quote = null;
829
+ let index = 0;
830
+ while (index < text.length) {
831
+ const char = text[index] ?? "";
832
+ if (quote) {
833
+ if (char === quote && text[index - 1] !== "\\") quote = null;
834
+ index += 1;
835
+ continue;
836
+ }
837
+ if (char === '"' || char === "'") {
838
+ quote = char;
839
+ index += 1;
840
+ continue;
841
+ }
842
+ if (depth > 0) {
843
+ if (char === "[" || char === "(" || char === "{") depth += 1;
844
+ else if (char === "]" || char === ")" || char === "}") depth -= 1;
845
+ index += 1;
846
+ continue;
847
+ }
848
+ if (/\s/.test(char) || char === "&" || char === ";") {
849
+ index += 1;
850
+ continue;
851
+ }
852
+ const idMatch = new RegExp(`^${ID}`).exec(text.slice(index));
853
+ if (!idMatch) {
854
+ index += 1;
855
+ continue;
856
+ }
857
+ const id = idMatch[0];
858
+ const idFrom = base + index;
859
+ let cursor = index + id.length;
860
+ while (cursor < text.length && /\s/.test(text[cursor] ?? "")) cursor += 1;
861
+ const shape = readShape(text, cursor);
862
+ if (shape) {
863
+ nodes.push({
864
+ id,
865
+ label: cleanLabel(shape.label),
866
+ defined: true,
867
+ from: idFrom,
868
+ to: idFrom + id.length,
869
+ line: lineNo,
870
+ column: index + 1
871
+ });
872
+ index = shape.end;
873
+ continue;
874
+ }
875
+ nodes.push({
876
+ id,
877
+ label: null,
878
+ defined,
879
+ from: idFrom,
880
+ to: idFrom + id.length,
881
+ line: lineNo,
882
+ column: index + 1
883
+ });
884
+ index = cursor;
885
+ }
886
+ return nodes;
887
+ }
888
+ function readShape(text, index) {
889
+ if (text.startsWith("@{", index)) {
890
+ const end = text.indexOf("}", index + 2);
891
+ if (end === -1) return null;
892
+ const inner = text.slice(index + 2, end);
893
+ const labeled = /label\s*:\s*(?:"([^"]*)"|([^,}]+))/.exec(inner);
894
+ return { label: (labeled?.[1] ?? labeled?.[2] ?? "").trim(), end: end + 1 };
895
+ }
896
+ const pairs = [
897
+ ["[[", ["]]"]],
898
+ ["[(", [")]"]],
899
+ ["([", ["])"]],
900
+ ["((", ["))"]],
901
+ ["[/", ["/]", "\\]"]],
902
+ ["[\\", ["\\]", "/]"]],
903
+ ["{{", ["}}"]],
904
+ ["[", ["]"]],
905
+ ["(", [")"]],
906
+ ["{", ["}"]],
907
+ [">", ["]"]]
908
+ ];
909
+ for (const [open, closes] of pairs) {
910
+ if (!text.startsWith(open, index)) continue;
911
+ const found = findCloser(text, index + open.length, open, closes);
912
+ if (!found) return null;
913
+ return { label: text.slice(index + open.length, found), end: found + (closes.find((close) => text.startsWith(close, found))?.length ?? 1) };
914
+ }
915
+ return null;
916
+ }
917
+ function findCloser(text, from, open, closes) {
918
+ let depth = 1;
919
+ for (let index = from; index < text.length; index += 1) {
920
+ if (text.startsWith(open, index) && open !== ">") {
921
+ depth += 1;
922
+ index += open.length - 1;
923
+ continue;
924
+ }
925
+ const close = closes.find((item) => text.startsWith(item, index));
926
+ if (!close) continue;
927
+ depth -= 1;
928
+ if (depth === 0) return index;
929
+ index += close.length - 1;
930
+ }
931
+ return null;
932
+ }
933
+ function cleanLabel(label) {
934
+ const trimmed = label.trim();
935
+ if (trimmed.length >= 2 && (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'"))) {
936
+ return trimmed.slice(1, -1).trim();
937
+ }
938
+ return trimmed;
939
+ }
940
+ var CLASS_ARROWS = [
941
+ "<|--|>",
942
+ "--|>",
943
+ "<|--",
944
+ "<|..",
945
+ "*--",
946
+ "--*",
947
+ "o--",
948
+ "--o",
949
+ "<-->",
950
+ "-->",
951
+ "<--",
952
+ "..|>",
953
+ "<|..",
954
+ "..>",
955
+ "<..",
956
+ "--",
957
+ ".."
958
+ ];
959
+ var CLASS_SKIP = /* @__PURE__ */ new Set([
960
+ "classdiagram",
961
+ "direction",
962
+ "note",
963
+ "style",
964
+ "cssclass",
965
+ "classdef",
966
+ "click",
967
+ "link",
968
+ "callback",
969
+ "acctitle",
970
+ "accdescr"
971
+ ]);
972
+ function scanClassDiagram(source) {
973
+ const decls = [];
974
+ const declared = [];
975
+ const uses = [];
976
+ let depth = 0;
977
+ walkBody(source, (line, lineStart) => {
978
+ const word = firstWord(line);
979
+ if (word === "namespace") return;
980
+ if (depth === 0 && !CLASS_SKIP.has(word)) {
981
+ if (word === "class") {
982
+ const decl = readClassDeclaration(source, line, lineStart);
983
+ if (decl) {
984
+ decls.push(decl);
985
+ declared.push(decl.id);
986
+ }
987
+ } else {
988
+ const arrow = findClassArrow(line);
989
+ if (arrow) {
990
+ const left = lastClassToken(line.slice(0, arrow.index));
991
+ const rightAt = arrow.index + arrow.length;
992
+ const right = firstClassToken(line.slice(rightAt));
993
+ if (left) uses.push(classUse(source, lineStart, left));
994
+ if (right) {
995
+ uses.push(classUse(source, lineStart, { id: right.id, from: right.from + rightAt, to: right.to + rightAt }));
996
+ }
997
+ } else {
998
+ const member = readClassMember(line);
999
+ if (member) declared.push(member.id);
1000
+ }
1001
+ }
1002
+ }
1003
+ depth = Math.max(0, depth + netBraces(line));
1004
+ });
1005
+ return { decls, declared, uses };
1006
+ }
1007
+ function duplicateClasses(scan) {
1008
+ const groups = /* @__PURE__ */ new Map();
1009
+ const used = new Set(scan.declared);
1010
+ for (const use of scan.uses) used.add(use.id);
1011
+ for (const decl of scan.decls) {
1012
+ used.add(decl.id);
1013
+ const list = groups.get(decl.id) ?? [];
1014
+ list.push(decl);
1015
+ groups.set(decl.id, list);
1016
+ }
1017
+ const diagnostics = [];
1018
+ for (const [id, decls] of groups) {
1019
+ let explicit = null;
1020
+ let sawUnlabeled = false;
1021
+ let origin = null;
1022
+ for (const decl of decls) {
1023
+ if (!origin) origin = decl;
1024
+ if (decl.label == null) {
1025
+ sawUnlabeled = true;
1026
+ continue;
1027
+ }
1028
+ if (explicit == null) {
1029
+ if (sawUnlabeled && decl.label !== id && origin) {
1030
+ diagnostics.push(duplicateClassDiagnostic(id, decl, id, origin, used));
1031
+ }
1032
+ explicit = decl.label;
1033
+ if (!sawUnlabeled) origin = decl;
1034
+ continue;
1035
+ }
1036
+ if (decl.label !== explicit && origin) diagnostics.push(duplicateClassDiagnostic(id, decl, explicit, origin, used));
1037
+ }
1038
+ }
1039
+ return diagnostics;
1040
+ }
1041
+ function duplicateClassDiagnostic(id, decl, firstLabel, origin, used) {
1042
+ const nextId = freshId(id, used);
1043
+ used.add(nextId);
1044
+ return {
1045
+ ruleId: "duplicate-class",
1046
+ severity: "warning",
1047
+ subject: id,
1048
+ message: `Class "${id}" is defined again with a different label ("${decl.label || "empty"}"). The first label is "${firstLabel || "empty"}".`,
1049
+ from: decl.from,
1050
+ to: decl.to,
1051
+ line: decl.line,
1052
+ column: decl.column,
1053
+ fixes: [
1054
+ {
1055
+ id: "rename-duplicate",
1056
+ title: `Rename to ${formatClassId(nextId)}`,
1057
+ edits: [{ from: decl.from, to: decl.to, insert: formatClassId(nextId) }]
1058
+ },
1059
+ {
1060
+ id: "jump-to-definition",
1061
+ title: "Jump to definition",
1062
+ edits: [],
1063
+ jump: { from: origin.from, to: origin.to }
1064
+ }
1065
+ ]
1066
+ };
1067
+ }
1068
+ function undeclaredClasses(scan) {
1069
+ const declared = new Set(scan.declared);
1070
+ if (declared.size === 0) return [];
1071
+ const diagnostics = [];
1072
+ const seen = /* @__PURE__ */ new Set();
1073
+ for (const use of scan.uses) {
1074
+ if (!use.id || declared.has(use.id) || seen.has(use.id)) continue;
1075
+ seen.add(use.id);
1076
+ diagnostics.push({
1077
+ ruleId: "undeclared-class",
1078
+ severity: "warning",
1079
+ subject: use.id,
1080
+ message: `This relationship uses "${use.id}", which was never declared. That is often a typo.`,
1081
+ from: use.from,
1082
+ to: use.to,
1083
+ line: use.line,
1084
+ column: use.column,
1085
+ fixes: [
1086
+ {
1087
+ id: "declare-class",
1088
+ title: `Declare class ${use.id}`,
1089
+ edits: [{ from: use.lineStart, to: use.lineStart, insert: `${use.indent}class ${formatClassId(use.id)}
1090
+ ` }]
1091
+ }
1092
+ ]
1093
+ });
1094
+ }
1095
+ return diagnostics;
1096
+ }
1097
+ var ER_SKIP = /* @__PURE__ */ new Set(["erdiagram", "direction", "style", "classdef", "click", "acctitle", "accdescr", "title"]);
1098
+ function scanErDiagram(source) {
1099
+ const entities = [];
1100
+ const attributes = [];
1101
+ const uses = [];
1102
+ let current = null;
1103
+ walkBody(source, (line, lineStart) => {
1104
+ if (current) {
1105
+ if (line.trim() === "}") {
1106
+ current = null;
1107
+ return;
1108
+ }
1109
+ const attribute = readAttribute(line);
1110
+ if (attribute) {
1111
+ const statement = lineStatementSpan(source, lineStart, line.length);
1112
+ attributes.push({
1113
+ ...pointSpan(source, lineStart + attribute.from, lineStart + attribute.to),
1114
+ entity: current,
1115
+ name: attribute.name,
1116
+ statementFrom: statement.from,
1117
+ statementTo: statement.to
1118
+ });
1119
+ }
1120
+ return;
1121
+ }
1122
+ if (ER_SKIP.has(firstWord(line))) return;
1123
+ const relation = readErRelationship(line);
1124
+ if (relation) {
1125
+ for (const side of [relation.left, relation.right]) {
1126
+ uses.push({
1127
+ ...pointSpan(source, lineStart + side.from, lineStart + side.to),
1128
+ id: side.id,
1129
+ lineStart,
1130
+ indent: lineIndent(source, lineStart)
1131
+ });
1132
+ }
1133
+ return;
1134
+ }
1135
+ const entity = readBareEntity(line);
1136
+ if (!entity) return;
1137
+ entities.push({
1138
+ ...pointSpan(source, lineStart + entity.from, lineStart + entity.to),
1139
+ id: entity.id,
1140
+ lineStart,
1141
+ indent: lineIndent(source, lineStart)
1142
+ });
1143
+ if (entity.opensBlock) current = entity.id;
1144
+ });
1145
+ return { entities, attributes, uses };
1146
+ }
1147
+ function duplicateAttributes(scan) {
1148
+ const seen = /* @__PURE__ */ new Set();
1149
+ const diagnostics = [];
1150
+ for (const attribute of scan.attributes) {
1151
+ const key = `${attribute.entity}\0${attribute.name}`;
1152
+ if (!seen.has(key)) {
1153
+ seen.add(key);
1154
+ continue;
1155
+ }
1156
+ diagnostics.push({
1157
+ ruleId: "duplicate-attribute",
1158
+ severity: "warning",
1159
+ subject: attribute.name,
1160
+ message: `Attribute "${attribute.name}" is listed again on "${attribute.entity}".`,
1161
+ from: attribute.from,
1162
+ to: attribute.to,
1163
+ line: attribute.line,
1164
+ column: attribute.column,
1165
+ fixes: [
1166
+ {
1167
+ id: "remove-attribute",
1168
+ title: "Remove duplicate attribute",
1169
+ edits: [{ from: attribute.statementFrom, to: attribute.statementTo, insert: "" }]
1170
+ }
1171
+ ]
1172
+ });
1173
+ }
1174
+ return diagnostics;
1175
+ }
1176
+ function undeclaredEntities(scan) {
1177
+ if (scan.entities.length === 0) return [];
1178
+ const declared = new Set(scan.entities.map((entity) => entity.id));
1179
+ const diagnostics = [];
1180
+ const seen = /* @__PURE__ */ new Set();
1181
+ for (const use of scan.uses) {
1182
+ if (!use.id || declared.has(use.id) || seen.has(use.id)) continue;
1183
+ seen.add(use.id);
1184
+ diagnostics.push({
1185
+ ruleId: "undeclared-entity",
1186
+ severity: "warning",
1187
+ subject: use.id,
1188
+ message: `This relationship uses "${use.id}", which was never declared. That is often a typo.`,
1189
+ from: use.from,
1190
+ to: use.to,
1191
+ line: use.line,
1192
+ column: use.column,
1193
+ fixes: [
1194
+ {
1195
+ id: "declare-entity",
1196
+ title: `Declare entity ${use.id}`,
1197
+ edits: [{ from: use.lineStart, to: use.lineStart, insert: `${use.indent}${formatEntityId(use.id)}
1198
+ ` }]
1199
+ }
1200
+ ]
1201
+ });
1202
+ }
1203
+ return diagnostics;
1204
+ }
1205
+ var GANTT_TAGS = /* @__PURE__ */ new Set(["active", "done", "crit", "milestone", "vert"]);
1206
+ var GANTT_SKIP = /* @__PURE__ */ new Set([
1207
+ "gantt",
1208
+ "title",
1209
+ "section",
1210
+ "axisformat",
1211
+ "tickinterval",
1212
+ "weekend",
1213
+ "weekday",
1214
+ "todaymarker",
1215
+ "inclusiveenddates",
1216
+ "topaxis",
1217
+ "acctitle",
1218
+ "accdescr"
1219
+ ]);
1220
+ var WEEKDAYS = /* @__PURE__ */ new Set(["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "weekends"]);
1221
+ function scanGantt(source) {
1222
+ const tasks = [];
1223
+ const checked = [];
1224
+ let formatLabel = "YYYY-MM-DD";
1225
+ let checker = compileDateFormat(formatLabel);
1226
+ const noteDate = (token) => {
1227
+ if (!checker) return;
1228
+ checked.push({ ...token, verdict: checker(token.text), format: formatLabel });
1229
+ };
1230
+ walkBody(source, (line, lineStart) => {
1231
+ const word = firstWord(line);
1232
+ if (word === "dateformat") {
1233
+ const format = line.replace(/^\s*dateFormat\s+/i, "").trim();
1234
+ formatLabel = format || formatLabel;
1235
+ checker = compileDateFormat(format);
1236
+ return;
1237
+ }
1238
+ if (word === "excludes") {
1239
+ const prefix = /^\s*excludes\s+/i.exec(line);
1240
+ const rest = line.slice(prefix?.[0].length ?? 0);
1241
+ for (const token of textTokens(rest)) {
1242
+ if (WEEKDAYS.has(token.text.toLowerCase()) || !/\d/.test(token.text)) continue;
1243
+ const from = lineStart + (prefix?.[0].length ?? 0) + token.from;
1244
+ noteDate({ ...pointSpan(source, from, from + token.text.length), text: token.text });
1245
+ }
1246
+ return;
1247
+ }
1248
+ if (GANTT_SKIP.has(word) || !line.includes(":")) return;
1249
+ const colon = line.indexOf(":");
1250
+ const data = line.slice(colon + 1);
1251
+ const parts = data.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
1252
+ while (parts.length > 0 && GANTT_TAGS.has((parts[0] ?? "").toLowerCase())) parts.shift();
1253
+ let id = null;
1254
+ let start = "";
1255
+ let end = "";
1256
+ if (parts.length >= 3) {
1257
+ id = parts[0] ?? null;
1258
+ start = parts[1] ?? "";
1259
+ end = parts[2] ?? "";
1260
+ } else if (parts.length === 2) {
1261
+ start = parts[0] ?? "";
1262
+ end = parts[1] ?? "";
1263
+ } else if (parts.length === 1) {
1264
+ end = parts[0] ?? "";
1265
+ }
1266
+ const deps = [];
1267
+ const dates2 = [];
1268
+ let searchFrom = 0;
1269
+ const take = (slot, role) => {
1270
+ if (!slot) return;
1271
+ const at = data.indexOf(slot, searchFrom);
1272
+ if (at < 0) return;
1273
+ searchFrom = at + slot.length;
1274
+ collectGanttSlot(source, lineStart + colon + 1 + at, slot, role, deps, dates2);
1275
+ };
1276
+ take(start, "start");
1277
+ take(end, "end");
1278
+ for (const date of dates2) noteDate(date);
1279
+ tasks.push({ id, deps });
1280
+ });
1281
+ const ids = new Set(tasks.flatMap((task) => task.id ? [task.id] : []));
1282
+ const dependencies = [];
1283
+ const seenDeps = /* @__PURE__ */ new Set();
1284
+ for (const task of tasks) {
1285
+ for (const dep of task.deps) {
1286
+ const key = `${dep.from}:${dep.id}`;
1287
+ if (ids.has(dep.id) || seenDeps.has(key)) continue;
1288
+ seenDeps.add(key);
1289
+ dependencies.push({
1290
+ ruleId: "missing-dependency",
1291
+ severity: "warning",
1292
+ subject: dep.id,
1293
+ message: `This task depends on "${dep.id}", which is not a task id in this diagram.`,
1294
+ from: dep.from,
1295
+ to: dep.to,
1296
+ line: dep.line,
1297
+ column: dep.column,
1298
+ fixes: []
1299
+ });
1300
+ }
1301
+ }
1302
+ const dates = [];
1303
+ for (const token of checked) {
1304
+ if (token.verdict === "ok") continue;
1305
+ dates.push({
1306
+ ruleId: "invalid-date",
1307
+ severity: "warning",
1308
+ subject: token.text,
1309
+ message: token.verdict === "calendar" ? `The date "${token.text}" is not a real calendar date.` : `The value "${token.text}" does not match ${token.format}.`,
1310
+ from: token.from,
1311
+ to: token.to,
1312
+ line: token.line,
1313
+ column: token.column,
1314
+ fixes: []
1315
+ });
1316
+ }
1317
+ return { dependencies, dates };
1318
+ }
1319
+ function scanMindmap(source) {
1320
+ const nodes = [];
1321
+ walkBody(source, (line, lineStart) => {
1322
+ if (/^\s*mindmap\b/i.test(line) || /^\s*::/.test(line)) return;
1323
+ const lead = line.length - line.trimStart().length;
1324
+ const body = line.trim();
1325
+ if (!body) return;
1326
+ const parsed = mindmapLabel(body);
1327
+ const statement = lineStatementSpan(source, lineStart, line.length);
1328
+ const label = parsed.label.trim();
1329
+ const from = label ? lineStart + lead + parsed.from : lineStart + lead;
1330
+ const to = label ? lineStart + lead + parsed.to : lineStart + lead + body.length;
1331
+ nodes.push({
1332
+ indent: leadingIndent(line),
1333
+ label,
1334
+ span: pointSpan(source, from, to),
1335
+ statementFrom: statement.from,
1336
+ statementTo: statement.to
1337
+ });
1338
+ });
1339
+ const duplicates = [];
1340
+ const empties = [];
1341
+ const stack = [{ indent: -1, labels: /* @__PURE__ */ new Set() }];
1342
+ for (let index = 0; index < nodes.length; index += 1) {
1343
+ const node = nodes[index];
1344
+ if (!node) continue;
1345
+ while (stack.length > 1 && (stack[stack.length - 1]?.indent ?? -1) >= node.indent) stack.pop();
1346
+ const parent = stack[stack.length - 1];
1347
+ const removable = !hasChild(nodes, index);
1348
+ const remove = (title) => removable ? [{ id: "remove-node", title, edits: [{ from: node.statementFrom, to: node.statementTo, insert: "" }] }] : [];
1349
+ if (!node.label) {
1350
+ empties.push({
1351
+ ruleId: "empty-node",
1352
+ severity: "warning",
1353
+ message: "This mindmap node has no text.",
1354
+ ...node.span,
1355
+ fixes: remove("Remove empty node")
1356
+ });
1357
+ } else if (parent?.labels.has(node.label)) {
1358
+ duplicates.push({
1359
+ ruleId: "duplicate-sibling",
1360
+ severity: "warning",
1361
+ subject: node.label,
1362
+ message: `Mindmap node "${node.label}" is repeated under the same parent.`,
1363
+ ...node.span,
1364
+ fixes: remove("Remove duplicate")
1365
+ });
1366
+ } else {
1367
+ parent?.labels.add(node.label);
1368
+ }
1369
+ stack.push({ indent: node.indent, labels: /* @__PURE__ */ new Set() });
1370
+ }
1371
+ return { duplicates, empties };
1372
+ }
1373
+ function scanTimeline(source) {
1374
+ const duplicates = [];
1375
+ const empties = [];
1376
+ let events = /* @__PURE__ */ new Set();
1377
+ walkBody(source, (line, lineStart) => {
1378
+ const word = firstWord(line);
1379
+ if (word === "timeline" || word === "title" || word === "acctitle" || word === "accdescr") return;
1380
+ if (word === "section") {
1381
+ events = /* @__PURE__ */ new Set();
1382
+ return;
1383
+ }
1384
+ const pieces = splitTimeline(line);
1385
+ if (!pieces) return;
1386
+ const statement = lineStatementSpan(source, lineStart, line.length);
1387
+ if (pieces.period) events = /* @__PURE__ */ new Set();
1388
+ for (const event of pieces.events) {
1389
+ const text = event.text.trim();
1390
+ const span = pointSpan(source, lineStart + event.from, lineStart + event.to);
1391
+ if (!text) {
1392
+ empties.push({
1393
+ ruleId: "empty-node",
1394
+ severity: "warning",
1395
+ message: "This timeline event has no text.",
1396
+ ...span,
1397
+ fixes: [timelineRemoval(event, lineStart, statement, "Remove empty node")]
1398
+ });
1399
+ continue;
1400
+ }
1401
+ if (events.has(text)) {
1402
+ duplicates.push({
1403
+ ruleId: "duplicate-sibling",
1404
+ severity: "warning",
1405
+ subject: text,
1406
+ message: `Timeline event "${text}" is repeated in this period.`,
1407
+ ...span,
1408
+ fixes: [timelineRemoval(event, lineStart, statement, "Remove duplicate")]
1409
+ });
1410
+ continue;
1411
+ }
1412
+ events.add(text);
1413
+ }
1414
+ });
1415
+ return { duplicates, empties };
1416
+ }
1417
+ function walkBody(source, visit) {
1418
+ const start = bodyStart(source);
1419
+ const body = parseDiagram(source).body;
1420
+ eachLine(source, start, start + body.length, (line, lineStart, lineNo) => {
1421
+ if (!line.trim() || line.trimStart().startsWith("%%")) return;
1422
+ visit(line, lineStart, lineNo);
1423
+ });
1424
+ }
1425
+ function firstWord(line) {
1426
+ return /^\s*([A-Za-z][\w-]*)/.exec(line)?.[1]?.toLowerCase() ?? "";
1427
+ }
1428
+ function readClassDeclaration(source, line, lineStart) {
1429
+ const match = /^\s*class\s+/i.exec(line);
1430
+ if (!match) return null;
1431
+ const token = firstClassToken(line.slice(match[0].length));
1432
+ if (!token) return null;
1433
+ const idFrom = match[0].length + token.from;
1434
+ let cursor = match[0].length + token.next;
1435
+ const bracket = readBracketLabel(line, cursor);
1436
+ const label = bracket ? bracket.label : null;
1437
+ return { ...pointSpan(source, lineStart + idFrom, lineStart + idFrom + (token.to - token.from)), id: token.id, label };
1438
+ }
1439
+ function readClassMember(line) {
1440
+ const colon = findUnquotedColon(line);
1441
+ if (colon == null) return null;
1442
+ const tokens = classTokens(line.slice(0, colon));
1443
+ if (tokens.length !== 1) return null;
1444
+ return { id: tokens[0]?.id ?? "" };
1445
+ }
1446
+ function findClassArrow(line) {
1447
+ let quote = null;
1448
+ let tick = false;
1449
+ for (let index = 0; index < line.length; index += 1) {
1450
+ const char = line[index] ?? "";
1451
+ if (tick) {
1452
+ if (char === "`") tick = false;
1453
+ continue;
1454
+ }
1455
+ if (quote) {
1456
+ if (char === quote && line[index - 1] !== "\\") quote = null;
1457
+ continue;
1458
+ }
1459
+ if (char === "`") {
1460
+ tick = true;
1461
+ continue;
1462
+ }
1463
+ if (char === '"' || char === "'") {
1464
+ quote = char;
1465
+ continue;
1466
+ }
1467
+ for (const arrow of CLASS_ARROWS) {
1468
+ if (line.startsWith(arrow, index)) return { index, length: arrow.length };
1469
+ }
1470
+ }
1471
+ return null;
1472
+ }
1473
+ function classTokens(text) {
1474
+ const tokens = [];
1475
+ let index = 0;
1476
+ while (index < text.length) {
1477
+ const found = firstClassToken(text.slice(index));
1478
+ if (!found) break;
1479
+ tokens.push({ id: found.id, from: index + found.from, to: index + found.to, next: index + found.next });
1480
+ index += found.next > found.from ? found.next : found.to + 1;
1481
+ if (found.next <= found.from) break;
1482
+ }
1483
+ return tokens;
1484
+ }
1485
+ function firstClassToken(text) {
1486
+ return classTokenAt(text, true);
1487
+ }
1488
+ function lastClassToken(text) {
1489
+ const tokens = classTokens(text);
1490
+ return tokens[tokens.length - 1] ?? null;
1491
+ }
1492
+ function classTokenAt(text, firstOnly) {
1493
+ let quote = null;
1494
+ let tick = false;
1495
+ for (let index = 0; index < text.length; index += 1) {
1496
+ const char = text[index] ?? "";
1497
+ if (tick) {
1498
+ if (char === "`") tick = false;
1499
+ continue;
1500
+ }
1501
+ if (quote) {
1502
+ if (char === quote) quote = null;
1503
+ continue;
1504
+ }
1505
+ if (char === "`") {
1506
+ const end = text.indexOf("`", index + 1);
1507
+ if (end < 0) return null;
1508
+ const token = { id: text.slice(index + 1, end), from: index, to: end + 1, next: end + 1 };
1509
+ if (firstOnly) return token;
1510
+ tick = true;
1511
+ index = end;
1512
+ continue;
1513
+ }
1514
+ if (char === '"' || char === "'") {
1515
+ quote = char;
1516
+ continue;
1517
+ }
1518
+ const match = /^[\p{L}_][\p{L}\p{N}_-]*/u.exec(text.slice(index));
1519
+ if (!match) continue;
1520
+ const id = match[0];
1521
+ let next = index + id.length;
1522
+ if (text[next] === "~") next = skipGeneric(text, next);
1523
+ return { id, from: index, to: index + id.length, next };
1524
+ }
1525
+ return null;
1526
+ }
1527
+ function skipGeneric(text, start) {
1528
+ let last = start;
1529
+ for (let index = start + 1; index < text.length; index += 1) {
1530
+ const char = text[index] ?? "";
1531
+ if (/[\s[{}\]]/.test(char)) break;
1532
+ if (char === "~") last = index;
1533
+ }
1534
+ return last > start ? last + 1 : start;
1535
+ }
1536
+ function readBracketLabel(text, index) {
1537
+ if (text[index] !== "[") return null;
1538
+ if (text[index + 1] === '"') {
1539
+ const endQuote = text.indexOf('"', index + 2);
1540
+ if (endQuote < 0 || text[endQuote + 1] !== "]") return null;
1541
+ return { label: text.slice(index + 2, endQuote) };
1542
+ }
1543
+ const close = text.indexOf("]", index + 1);
1544
+ if (close < 0) return null;
1545
+ return { label: text.slice(index + 1, close).trim() };
1546
+ }
1547
+ function classUse(source, lineStart, token) {
1548
+ return {
1549
+ ...pointSpan(source, lineStart + token.from, lineStart + token.to),
1550
+ id: token.id,
1551
+ lineStart,
1552
+ indent: lineIndent(source, lineStart)
1553
+ };
1554
+ }
1555
+ function formatClassId(id) {
1556
+ if (/^[\p{L}_][\p{L}\p{N}_-]*$/u.test(id)) return id;
1557
+ return `\`${id.replace(/`/g, "")}\``;
1558
+ }
1559
+ function formatEntityId(id) {
1560
+ if (/^[\p{L}\p{N}_][\p{L}\p{N}_.-]*$/u.test(id)) return id;
1561
+ return `"${id.replace(/"/g, "")}"`;
1562
+ }
1563
+ function netBraces(line) {
1564
+ let net = 0;
1565
+ let quote = null;
1566
+ let tick = false;
1567
+ for (let index = 0; index < line.length; index += 1) {
1568
+ const char = line[index] ?? "";
1569
+ if (tick) {
1570
+ if (char === "`") tick = false;
1571
+ continue;
1572
+ }
1573
+ if (quote) {
1574
+ if (char === quote && line[index - 1] !== "\\") quote = null;
1575
+ continue;
1576
+ }
1577
+ if (char === "`") {
1578
+ tick = true;
1579
+ continue;
1580
+ }
1581
+ if (char === '"' || char === "'") {
1582
+ quote = char;
1583
+ continue;
1584
+ }
1585
+ if (char === "{") net += 1;
1586
+ else if (char === "}") net -= 1;
1587
+ }
1588
+ return net;
1589
+ }
1590
+ function findUnquotedColon(line) {
1591
+ let quote = null;
1592
+ for (let index = 0; index < line.length; index += 1) {
1593
+ const char = line[index] ?? "";
1594
+ if (quote) {
1595
+ if (char === quote) quote = null;
1596
+ continue;
1597
+ }
1598
+ if (char === '"' || char === "'") {
1599
+ quote = char;
1600
+ continue;
1601
+ }
1602
+ if (char === ":") return index;
1603
+ }
1604
+ return null;
1605
+ }
1606
+ function readErRelationship(line) {
1607
+ const labelAt = findLabelSeparator(line);
1608
+ const body = labelAt == null ? line : line.slice(0, labelAt);
1609
+ const left = readEntityAt(body, 0);
1610
+ const right = readEntityFromEnd(body);
1611
+ if (!left || !right || right.from < left.next) return null;
1612
+ const middle = body.slice(left.next, right.from);
1613
+ if (!/--|\.\.|\sto\s/i.test(middle)) return null;
1614
+ return { left, right };
1615
+ }
1616
+ function readBareEntity(line) {
1617
+ const token = readEntityAt(line, 0);
1618
+ if (!token) return null;
1619
+ const rest = line.slice(token.next).trim();
1620
+ if (rest === "") return { ...token, opensBlock: false };
1621
+ if (rest === "{" || rest.startsWith("{") && !rest.includes("}")) return { ...token, opensBlock: true };
1622
+ return null;
1623
+ }
1624
+ function readEntityAt(text, index) {
1625
+ let cursor = index;
1626
+ while (cursor < text.length && /\s/.test(text[cursor] ?? "")) cursor += 1;
1627
+ if (cursor >= text.length) return null;
1628
+ let id = "";
1629
+ let from = cursor;
1630
+ let to = cursor;
1631
+ if (text[cursor] === '"') {
1632
+ const end = text.indexOf('"', cursor + 1);
1633
+ if (end < 0) return null;
1634
+ id = text.slice(cursor + 1, end);
1635
+ from = cursor + 1;
1636
+ to = end;
1637
+ cursor = end + 1;
1638
+ } else {
1639
+ const match = /^[\p{L}\p{N}_][\p{L}\p{N}_.-]*/u.exec(text.slice(cursor));
1640
+ if (!match) return null;
1641
+ id = match[0];
1642
+ from = cursor;
1643
+ to = cursor + id.length;
1644
+ cursor = to;
1645
+ }
1646
+ let aliasAt = cursor;
1647
+ while (aliasAt < text.length && /\s/.test(text[aliasAt] ?? "")) aliasAt += 1;
1648
+ if (text[aliasAt] === "[") {
1649
+ const close = text.indexOf("]", aliasAt + 1);
1650
+ if (close >= 0) cursor = close + 1;
1651
+ }
1652
+ return { id, from, to, next: cursor };
1653
+ }
1654
+ function readEntityFromEnd(text) {
1655
+ let end = text.length;
1656
+ while (end > 0 && /\s/.test(text[end - 1] ?? "")) end -= 1;
1657
+ if (end === 0) return null;
1658
+ if (text[end - 1] === '"') {
1659
+ const start2 = text.lastIndexOf('"', end - 2);
1660
+ if (start2 < 0) return null;
1661
+ return { id: text.slice(start2 + 1, end - 1), from: start2 + 1, to: end - 1 };
1662
+ }
1663
+ let start = end;
1664
+ while (start > 0 && /[\p{L}\p{N}_.-]/u.test(text[start - 1] ?? "")) start -= 1;
1665
+ if (start === end) return null;
1666
+ const id = text.slice(start, end);
1667
+ if (!/^[\p{L}\p{N}_]/u.test(id)) return null;
1668
+ return { id, from: start, to: end };
1669
+ }
1670
+ function findLabelSeparator(line) {
1671
+ let quote = false;
1672
+ for (let index = 0; index < line.length - 2; index += 1) {
1673
+ if (line[index] === '"') {
1674
+ quote = !quote;
1675
+ continue;
1676
+ }
1677
+ if (!quote && line.startsWith(" : ", index)) return index;
1678
+ }
1679
+ return null;
1680
+ }
1681
+ function readAttribute(line) {
1682
+ const match = /^\s*([\p{L}][\p{L}\p{N}_[\]().?-]*)\s+\*?([\p{L}\p{N}_][\p{L}\p{N}_.-]*)/u.exec(line);
1683
+ const name = match?.[2];
1684
+ if (!match || !name) return null;
1685
+ const from = match[0].lastIndexOf(name);
1686
+ if (from < 0) return null;
1687
+ return { name, from, to: from + name.length };
1688
+ }
1689
+ function collectGanttSlot(source, base, slot, role, deps, dates) {
1690
+ const keyword = /^(after|until)\b/i.exec(slot);
1691
+ if (keyword?.[0]) {
1692
+ let searchFrom = keyword[0].length;
1693
+ for (const id of slot.slice(keyword[0].length).trim().split(/\s+/)) {
1694
+ if (!id) continue;
1695
+ const at = slot.indexOf(id, searchFrom);
1696
+ if (at < 0) continue;
1697
+ deps.push({ ...pointSpan(source, base + at, base + at + id.length), id });
1698
+ searchFrom = at + id.length;
1699
+ }
1700
+ return;
1701
+ }
1702
+ if (role === "end" && isDuration(slot)) return;
1703
+ dates.push({ ...pointSpan(source, base, base + slot.length), text: slot });
1704
+ }
1705
+ function isDuration(value) {
1706
+ return /^\d+(?:\.\d+)?(?:ms|s|m|h|d|w|M|y)$/.test(value);
1707
+ }
1708
+ function compileDateFormat(format) {
1709
+ const trimmed = format.trim();
1710
+ if (trimmed === "x" || trimmed === "X") return (value) => /^\d+$/.test(value) ? "ok" : "shape";
1711
+ if (/MMM|DDD|ddd/.test(trimmed)) return null;
1712
+ const tokens = ["YYYY", "SSS", "YY", "MM", "DD", "HH", "mm", "ss"];
1713
+ let pattern = "";
1714
+ const groups = [];
1715
+ for (let index = 0; index < trimmed.length; ) {
1716
+ const token = tokens.find((item) => trimmed.startsWith(item, index));
1717
+ if (token) {
1718
+ const width = token === "YYYY" ? 4 : token === "SSS" ? 3 : 2;
1719
+ pattern += `(\\d{${width}})`;
1720
+ groups.push(token);
1721
+ index += token.length;
1722
+ continue;
1723
+ }
1724
+ const char = trimmed[index] ?? "";
1725
+ if (/[A-Za-z]/.test(char)) return null;
1726
+ pattern += escapeRegExp(char);
1727
+ index += 1;
1728
+ }
1729
+ if (groups.length === 0) return null;
1730
+ const regex = new RegExp(`^${pattern}$`);
1731
+ return (value) => {
1732
+ const match = regex.exec(value);
1733
+ if (!match) return "shape";
1734
+ return calendarOk(groups, match) ? "ok" : "calendar";
1735
+ };
1736
+ }
1737
+ function calendarOk(groups, match) {
1738
+ const read = (token) => {
1739
+ const index = groups.indexOf(token);
1740
+ if (index < 0) return null;
1741
+ return Number(match[index + 1]);
1742
+ };
1743
+ const month = read("MM");
1744
+ const day = read("DD");
1745
+ const hour = read("HH");
1746
+ const minute = read("mm");
1747
+ const second = read("ss");
1748
+ if (month != null && (month < 1 || month > 12)) return false;
1749
+ if (hour != null && hour > 23) return false;
1750
+ if (minute != null && minute > 59) return false;
1751
+ if (second != null && second > 59) return false;
1752
+ if (day == null) return true;
1753
+ if (day < 1 || day > 31) return false;
1754
+ if (month == null) return true;
1755
+ const year = read("YYYY") ?? (read("YY") != null ? 2e3 + read("YY") : null);
1756
+ if (year == null && month === 2 && day === 29) return true;
1757
+ const days = new Date(Date.UTC(year ?? 2e3, month, 0)).getUTCDate();
1758
+ return day <= days;
1759
+ }
1760
+ function textTokens(text) {
1761
+ const tokens = [];
1762
+ for (const match of text.matchAll(/\S+/g)) {
1763
+ if (match.index == null) continue;
1764
+ tokens.push({ text: match[0], from: match.index });
1765
+ }
1766
+ return tokens;
1767
+ }
1768
+ function mindmapLabel(body) {
1769
+ const id = /^[\p{L}_][\p{L}\p{N}_-]*/u.exec(body);
1770
+ const idLength = id?.[0].length ?? 0;
1771
+ const rest = body.slice(idLength);
1772
+ const pairs = [
1773
+ ["((", "))"],
1774
+ ["))", "(("],
1775
+ ["{{", "}}"],
1776
+ ["[", "]"],
1777
+ ["(", ")"],
1778
+ [")", "("]
1779
+ ];
1780
+ for (const [open, close] of pairs) {
1781
+ if (!rest.startsWith(open)) continue;
1782
+ const end = rest.lastIndexOf(close);
1783
+ if (end < open.length) continue;
1784
+ return { label: unwrapLabel(rest.slice(open.length, end)), from: idLength + open.length, to: idLength + end };
1785
+ }
1786
+ return { label: unwrapLabel(body), from: 0, to: body.length };
1787
+ }
1788
+ function unwrapLabel(label) {
1789
+ let text = label.trim();
1790
+ if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) text = text.slice(1, -1).trim();
1791
+ if (text.length >= 2 && text.startsWith("`") && text.endsWith("`")) text = text.slice(1, -1).trim();
1792
+ return text;
1793
+ }
1794
+ function leadingIndent(line) {
1795
+ const raw = /^[ \t]*/.exec(line)?.[0] ?? "";
1796
+ return raw.replace(/\t/g, " ").length;
1797
+ }
1798
+ function hasChild(nodes, index) {
1799
+ const node = nodes[index];
1800
+ if (!node) return false;
1801
+ for (let cursor = index + 1; cursor < nodes.length; cursor += 1) {
1802
+ const next = nodes[cursor];
1803
+ if (!next) continue;
1804
+ if (next.indent > node.indent) return true;
1805
+ return false;
1806
+ }
1807
+ return false;
1808
+ }
1809
+ function splitTimeline(line) {
1810
+ const marks = [];
1811
+ for (let index = 0; index < line.length; index += 1) {
1812
+ if (line[index] !== ":") continue;
1813
+ const before = index > 0 && /\s/.test(line[index - 1] ?? "");
1814
+ const after = index + 1 < line.length && /\s/.test(line[index + 1] ?? "");
1815
+ if (before || after || index === line.length - 1) marks.push(index);
1816
+ }
1817
+ if (marks.length === 0) return null;
1818
+ const headEnd = marks[0] ?? 0;
1819
+ const head = line.slice(0, headEnd).trim();
1820
+ const headAt = head ? line.indexOf(head) : 0;
1821
+ const period = head ? { text: head, from: headAt, to: headAt + head.length } : null;
1822
+ const events = [];
1823
+ for (let index = 0; index < marks.length; index += 1) {
1824
+ const mark = marks[index] ?? 0;
1825
+ const start = mark + 1;
1826
+ const end = index + 1 < marks.length ? marks[index + 1] ?? line.length : line.length;
1827
+ const raw = line.slice(start, end);
1828
+ const text = raw.trim();
1829
+ const local = text ? raw.indexOf(text) : 0;
1830
+ const from = text ? start + local : mark;
1831
+ const to = text ? from + text.length : mark + 1;
1832
+ let dropFrom = mark;
1833
+ if (dropFrom > 0 && /\s/.test(line[dropFrom - 1] ?? "")) dropFrom -= 1;
1834
+ events.push({
1835
+ text,
1836
+ from,
1837
+ to,
1838
+ dropFrom,
1839
+ dropTo: end,
1840
+ solo: period == null && marks.length === 1,
1841
+ only: marks.length === 1
1842
+ });
1843
+ }
1844
+ return { period, events };
1845
+ }
1846
+ function timelineRemoval(event, lineStart, statement, title) {
1847
+ if (event.solo || event.only && !event.text.trim()) {
1848
+ return { id: "remove-node", title, edits: [{ from: statement.from, to: statement.to, insert: "" }] };
1849
+ }
1850
+ return {
1851
+ id: "remove-node",
1852
+ title,
1853
+ edits: [{ from: lineStart + event.dropFrom, to: lineStart + event.dropTo, insert: "" }]
1854
+ };
1855
+ }
1856
+ function freshId(id, used) {
1857
+ for (let number = 2; number < 200; number += 1) {
1858
+ const next = `${id}${number}`;
1859
+ if (!used.has(next)) return next;
1860
+ }
1861
+ return `${id}_${used.size + 2}`;
1862
+ }
1863
+ function lineIndent(source, lineStart) {
1864
+ const match = /^[ \t]*/.exec(source.slice(lineStart));
1865
+ return match?.[0] ?? "";
1866
+ }
1867
+ function lineStatementSpan(source, lineStart, lineLength) {
1868
+ let to = lineStart + lineLength;
1869
+ if (source[to] === "\r") to += 1;
1870
+ if (source[to] === "\n") to += 1;
1871
+ return { from: lineStart, to };
1872
+ }
1873
+ function bodyStart(source) {
1874
+ const bom = source.charCodeAt(0) === 65279 ? 1 : 0;
1875
+ const text = bom ? source.slice(bom) : source;
1876
+ const body = parseDiagram(source).body;
1877
+ return bom + (text.length - body.length);
1878
+ }
1879
+ function eachLine(source, from, to, visit) {
1880
+ const end = Math.max(from, Math.min(to, source.length));
1881
+ let start = from;
1882
+ let number = lineNumberAt(source, from);
1883
+ for (let index = from; index <= end; index += 1) {
1884
+ if (index !== end && source[index] !== "\n") continue;
1885
+ let textEnd = index;
1886
+ if (textEnd > start && source[textEnd - 1] === "\r") textEnd -= 1;
1887
+ if (textEnd > start || index === end) visit(source.slice(start, textEnd), start, number);
1888
+ number += 1;
1889
+ start = index + 1;
1890
+ }
1891
+ }
1892
+ function lineNumberAt(source, offset) {
1893
+ let line = 1;
1894
+ for (let index = 0; index < offset && index < source.length; index += 1) {
1895
+ if (source[index] === "\n") line += 1;
1896
+ }
1897
+ return line;
1898
+ }
1899
+ function pointSpan(source, from, to) {
1900
+ const line = lineNumberAt(source, from);
1901
+ const lineStart = source.lastIndexOf("\n", from - 1) + 1;
1902
+ return { from, to: Math.max(to, from + 1), line, column: from - lineStart + 1 };
1903
+ }
1904
+ function lineSpan(source, line) {
1905
+ let number = 1;
1906
+ let start = 0;
1907
+ for (let index = 0; index <= source.length; index += 1) {
1908
+ if (index !== source.length && source[index] !== "\n") continue;
1909
+ if (number === line) {
1910
+ let textEnd = index;
1911
+ if (textEnd > start && source[textEnd - 1] === "\r") textEnd -= 1;
1912
+ const from = start;
1913
+ const to = Math.max(textEnd, from + 1);
1914
+ return { from, to, line, column: 1 };
1915
+ }
1916
+ number += 1;
1917
+ start = index + 1;
1918
+ }
1919
+ return { from: 0, to: Math.min(1, source.length), line: 1, column: 1 };
1920
+ }
1921
+ function indexOfToken(source, token) {
1922
+ const from = source.indexOf(token);
1923
+ if (from < 0) return null;
1924
+ return pointSpan(source, from, from + token.length);
1925
+ }
1926
+ function escapeRegExp(value) {
1927
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1928
+ }
1929
+
1930
+ // server/src/mermaidSyntax.ts
1931
+ async function mermaidSyntaxDiagnostic(source) {
1932
+ if (!source.trim()) return null;
1933
+ try {
1934
+ await mermaid.parse(source);
1935
+ return null;
1936
+ } catch (error) {
1937
+ if (isMermaidEnvironmentError(error)) return null;
1938
+ const message = error instanceof Error ? error.message : String(error);
1939
+ const hash = error && typeof error === "object" && "hash" in error ? error.hash : void 0;
1940
+ const hasLocation = typeof hash?.loc?.first_line === "number" && hash.loc.first_line > 0;
1941
+ if (!hasLocation && !/parse error on line/i.test(message)) return null;
1942
+ const located = locateParseError(error, source);
1943
+ return {
1944
+ ruleId: "parse",
1945
+ severity: "error",
1946
+ message: located.message,
1947
+ from: located.from,
1948
+ to: located.to,
1949
+ line: located.line,
1950
+ column: located.column,
1951
+ fixes: []
1952
+ };
1953
+ }
1954
+ }
1955
+ async function lintDiagramSource(source, options = {}) {
1956
+ const diagnostics = lintDiagram(source, options);
1957
+ const syntax = await mermaidSyntaxDiagnostic(source);
1958
+ if (!syntax) return diagnostics;
1959
+ return [...diagnostics, syntax].sort(
1960
+ (a, b) => a.from - b.from || a.line - b.line || String(a.ruleId).localeCompare(String(b.ruleId))
1961
+ );
1962
+ }
1963
+ export {
1964
+ lintDiagramSource,
1965
+ mermaidSyntaxDiagnostic
1966
+ };