axstack 0.75.0 → 0.76.0

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,549 @@
1
+ #!/usr/bin/env bun
2
+ import { mkdirSync } from 'node:fs';
3
+
4
+ const PELE_VERSION = '1.13.0';
5
+ const PELE_SHA256 = '37bea5005aa6d2dde929032ced5d2958cf642667cbc1fe675f9dfacf4ba15a51';
6
+ const PELE_PATH = `${import.meta.dir}/../vendor/pele/pele.js`;
7
+ const TARGET_WIDTH = 860;
8
+ const NATURAL_LABEL_SIZE = 16;
9
+ const MIN_LABEL_SIZE = 12;
10
+ const DENSE_OVERVIEW_EDGES = 25;
11
+ const DENSE_ELK_NOTE = 'dense ELK overview: needs zoom/pan in chat; geometry not measured (pinned pele ignores ELK)';
12
+ const NO_CLASSES = new Set(['sequenceDiagram', 'stateDiagram-v2', 'timeline']);
13
+ const STATUS_WORD = /\b(?:planned|unknown|retiring|open|partial|deprecated|proposed)\b/i;
14
+
15
+ const HELP = `Usage: bun mermaid-check.js [options] <file.md|file.mmd>
16
+
17
+ Check Mermaid source with pinned Pele ${PELE_VERSION}.
18
+ --expect Require at least one Mermaid fence (default)
19
+ --no-expect Allow Markdown without Mermaid fences
20
+ --overview Require an overview flowchart as block 1 (tiered TB by default)
21
+ --svg-out <dir> Write checked SVGs and print source and SVG SHA-256 digests
22
+ --pele <path> Use an alternate copy of the pinned renderer
23
+ --allow-type <type> Allow one additional type explicitly requested by the user
24
+ --help Show this help
25
+ Exit codes: 0 pass, 1 input/contract/render failure, 2 usage, 3 renderer missing or invalid.`;
26
+
27
+ const TYPES = new Set(['flowchart', 'sequenceDiagram', 'stateDiagram-v2', 'erDiagram', 'timeline']);
28
+ const SPACING = new Map([
29
+ ['flowchart', ['config.flowchart.nodeSpacing', 'config.flowchart.rankSpacing']],
30
+ ['sequenceDiagram', ['config.sequence.actorMargin', 'config.sequence.messageMargin']],
31
+ ]);
32
+ const NODE_STYLE = new Set(['fill', 'stroke', 'stroke-width', 'stroke-dasharray']);
33
+ const LINK_STYLE = new Set(['stroke-width']);
34
+ const QUOTED = /"(?:[^"\\]|\\.)*"/g;
35
+ const sha256 = (bytes) => new Bun.CryptoHasher('sha256').update(bytes).digest('hex');
36
+
37
+ function optionsFor(args) {
38
+ const options = { path: '', renderer: PELE_PATH, svgDir: '', extraType: '', expect: true, overview: false };
39
+ for (let index = 0; index < args.length; index++) {
40
+ const arg = args[index];
41
+ if (arg === '--expect' || arg === '--no-expect') {
42
+ options.expect = arg === '--expect';
43
+ } else if (arg === '--overview') {
44
+ options.overview = true;
45
+ } else if (arg === '--pele' || arg === '--svg-out' || arg === '--allow-type') {
46
+ const value = args[++index];
47
+ if (!value || value.startsWith('--')) return undefined;
48
+ if (arg === '--pele') options.renderer = value;
49
+ else if (arg === '--svg-out') options.svgDir = value;
50
+ else options.extraType = value;
51
+ } else if (arg.startsWith('-') || options.path) {
52
+ return undefined;
53
+ } else {
54
+ options.path = arg;
55
+ }
56
+ }
57
+ return /\.(?:mmd|md|markdown)$/i.test(options.path) ? options : undefined;
58
+ }
59
+
60
+ function markdownBlocks(markdown) {
61
+ const blocks = [];
62
+ const lines = markdown.split(/(?<=\n)/);
63
+ let fence;
64
+ for (const [index, line] of lines.entries()) {
65
+ const text = line.trimEnd();
66
+ if (fence) {
67
+ const marker = text.trimStart();
68
+ if (marker.startsWith(fence.marker) && [...marker].every((char) => char === fence.marker[0])) {
69
+ if (fence.mermaid) blocks.push({ source: fence.source, line: fence.line, firstLine: fence.line + 1 });
70
+ fence = undefined;
71
+ } else if (fence.mermaid) {
72
+ // Drop container indentation while preserving the payload's whitespace and line endings.
73
+ const indent = line.match(/^[ \t]*/)[0].length;
74
+ fence.source += line.slice(Math.min(indent, fence.indent));
75
+ }
76
+ continue;
77
+ }
78
+ const opening = text.match(/^([ \t]*(?:(?:[-+*]|\d+[.)])[ \t]+)?)(`{3,}|~{3,})(.*)$/);
79
+ if (!opening || (opening[2][0] === '`' && opening[3].includes('`'))) continue;
80
+ fence = {
81
+ marker: opening[2],
82
+ indent: opening[1].length,
83
+ mermaid: /^mermaid(?:\s|$)/i.test(opening[3].trim()),
84
+ line: index + 1,
85
+ source: '',
86
+ };
87
+ }
88
+ if (fence?.mermaid) throw new Error(`unclosed Mermaid fence at line ${fence.line}`);
89
+ return blocks;
90
+ }
91
+
92
+ async function loadRenderer(path) {
93
+ const bytes = await Bun.file(path).bytes();
94
+ if (sha256(bytes) !== PELE_SHA256) throw new Error(`hash mismatch for ${path}`);
95
+ // Import the verified bytes, even if the override path changes after the read.
96
+ const url = URL.createObjectURL(new Blob([bytes], { type: 'text/javascript' }));
97
+ try {
98
+ return await import(url);
99
+ } finally {
100
+ URL.revokeObjectURL(url);
101
+ }
102
+ }
103
+
104
+ function rejectSemicolon(label, text) {
105
+ if (!text?.includes(';')) return;
106
+ const hint = label === 'participant alias' ? 'use a comma or dash and move status to message text' : 'use a comma or dash';
107
+ throw new Error(`semicolon in ${label}; ${hint}`);
108
+ }
109
+
110
+ function sequenceText(line) {
111
+ const alias = line.match(/^(?:actor|participant)\s+\S+?(?:\s*@\{[^{}]*\})?\s+as\s+(.*)$/i);
112
+ if (alias) return ['participant alias', alias[1]];
113
+ const message = line.match(/^[^:\s]+\s*(?:<<)?-+[-<>x)]+\s*[^:\s]+\s*:\s*(.*)$/);
114
+ if (message) return ['sequence message', message[1]];
115
+ return [];
116
+ }
117
+
118
+ function withoutMermaidEntities(text) {
119
+ // Mermaid entities such as #42; use a semicolon as syntax.
120
+ return text.replace(/#(?:\d+|[a-z]+);/gi, '');
121
+ }
122
+
123
+ function textBeforeParse(type, line) {
124
+ if (type === 'sequenceDiagram') {
125
+ const [label, text] = sequenceText(line);
126
+ if (!label) return;
127
+ // Pele can read a quoted semicolon as a separator and accept the altered sequence.
128
+ for (const [quoted] of withoutMermaidEntities(text).matchAll(QUOTED)) rejectSemicolon(label, quoted);
129
+ }
130
+ if (type === 'stateDiagram-v2') {
131
+ const label = line.match(/^(?!acc(?:Title|Descr)\s*:)([^:\s]+(?:\s*-->\s*[^:\s]+)?)\s*:\s*(.*)$/i);
132
+ if (!label) return;
133
+ // Pele drops text after an ambiguous semicolon in a state label. Leave explicit next statements alone.
134
+ const text = withoutMermaidEntities(label[2]).split(/;\s*(?:(?:state|note|direction|class)\b|[^;\s]+\s*-->)/i)[0];
135
+ rejectSemicolon(label[1].includes('-->') ? 'edge label' : 'node label', text.replace(/;$/, ''));
136
+ }
137
+ }
138
+
139
+ function parseDiagram(pele, source, type) {
140
+ try {
141
+ return pele.parse(source);
142
+ } catch (error) {
143
+ if (error instanceof pele.PeleError && error.line) {
144
+ const line = source.split(/\r?\n/)[error.line - 1]?.trim() ?? '';
145
+ if (type === 'sequenceDiagram') {
146
+ const [label, text] = sequenceText(line);
147
+ if (label) rejectSemicolon(label, withoutMermaidEntities(text).replace(/;$/, ''));
148
+ }
149
+ if (type === 'erDiagram') {
150
+ const label = line.match(/^\S+\s+[^:\s]*[-.]{2}[^:\s]*\s+\S+\s*:\s*(.*)$/)?.[1];
151
+ if (label) rejectSemicolon('edge label', withoutMermaidEntities(label).replace(/;$/, ''));
152
+ }
153
+ }
154
+ throw error;
155
+ }
156
+ }
157
+
158
+ function frontmatterPaths(lines) {
159
+ const fields = new Map();
160
+ const stack = [{ path: '', indent: -1, childIndent: 0 }];
161
+ for (const raw of lines) {
162
+ const line = raw.trimEnd();
163
+ if (!line.trim() || line.trimStart().startsWith('#')) continue;
164
+ const entry = line.match(/^( *)([A-Za-z]\w*):(?: +(\S.*))?$/);
165
+ if (!entry) throw new Error('expected multiline frontmatter with nested maps and scalar values');
166
+ const [, spaces, key, value] = entry;
167
+ const indent = spaces.length;
168
+ while (stack.at(-1).indent >= indent) stack.pop();
169
+ const parent = stack.at(-1);
170
+ parent.childIndent ??= indent;
171
+ if (indent !== parent.childIndent) throw new Error('inconsistent indentation in frontmatter');
172
+ if (/^(?:theme|themeVariables|themeCSS|look|font\w*)$/i.test(key)) {
173
+ throw new Error(`${key} key is forbidden in frontmatter`);
174
+ }
175
+ const path = parent.path ? `${parent.path}.${key}` : key;
176
+ if (fields.has(path)) throw new Error(`duplicate frontmatter key: ${path}`);
177
+ if (/^[[{|>&*!]/.test(value ?? '')) throw new Error(`expected multiline frontmatter, not a flow mapping or special scalar at ${path}`);
178
+ fields.set(path, value);
179
+ if (!value) stack.push({ path, indent, childIndent: undefined });
180
+ }
181
+ return fields;
182
+ }
183
+
184
+ function checkFrontmatter(lines, type) {
185
+ const fields = frontmatterPaths(lines);
186
+ const spacing = SPACING.get(type) ?? [];
187
+ const node = type === 'flowchart' ? 'config.flowchart' : 'config.sequence';
188
+ const maps = spacing.length ? new Set(['config', node]) : new Set();
189
+ let elk = false;
190
+ for (const [path, value] of fields) {
191
+ if (maps.has(path)) {
192
+ if (value) throw new Error(`expected a multiline frontmatter map for ${path}`);
193
+ } else if (spacing.includes(path)) {
194
+ if (!/^\d+$/.test(value ?? '') || Number(value) < 40 || Number(value) > 150) {
195
+ throw new Error(`${path} must be an integer from 40 to 150`);
196
+ }
197
+ } else if (path === 'config.layout') {
198
+ if (type !== 'flowchart') throw new Error('config.layout is allowed only for flowchart');
199
+ if (!/^(elk|"elk"|'elk')$/.test(value ?? '')) throw new Error('config.layout must be elk');
200
+ elk = true;
201
+ } else if (path === 'config.flowchart.curve' && type === 'flowchart') {
202
+ if (!/^(?:step|linear|basis|(["'])(?:step|linear|basis)\1)$/.test(value ?? '')) {
203
+ throw new Error('config.flowchart.curve must be step, linear or basis');
204
+ }
205
+ } else if (path === 'title') {
206
+ if (!value) throw new Error('frontmatter title must be a scalar');
207
+ } else {
208
+ throw new Error(`unknown frontmatter key: ${path}`);
209
+ }
210
+ }
211
+ for (const key of spacing) {
212
+ if (!fields.has(key)) throw new Error(`required frontmatter key is missing: ${key}`);
213
+ }
214
+ return elk;
215
+ }
216
+
217
+ function strokeHue(value) {
218
+ const rgb = Bun.color(value, '{rgb}');
219
+ if (!rgb || typeof rgb === 'string') throw new Error(`stroke must be a colour with a measurable hue: ${value}`);
220
+ const [red, green, blue] = [rgb.r / 255, rgb.g / 255, rgb.b / 255];
221
+ const max = Math.max(red, green, blue);
222
+ const min = Math.min(red, green, blue);
223
+ const spread = max - min;
224
+ if (!spread || spread / (1 - Math.abs(max + min - 1)) <= 0.15) return undefined;
225
+ let sector = (red - green) / spread + 4;
226
+ if (max === red) sector = (green - blue) / spread;
227
+ else if (max === green) sector = (blue - red) / spread + 2;
228
+ return (sector * 60 + 360) % 360;
229
+ }
230
+
231
+ function checkAccentHues(hues) {
232
+ if (hues.length < 2) return;
233
+ const sorted = hues.toSorted((a, b) => a - b);
234
+ // The complement of the largest gap is the shortest arc covering every accent.
235
+ const maxGap = sorted.reduce((largest, hue, index) =>
236
+ index ? Math.max(largest, hue - sorted[index - 1]) : largest, 360 + sorted[0] - sorted.at(-1));
237
+ if (360 - maxGap > 30) throw new Error('use neutral grey strokes and one accent hue within ±15° per diagram');
238
+ }
239
+
240
+ function checkStyle(rule, kind, accentStrokes) {
241
+ const declaration = rule.match(/^\w+\s+[^\s,]+(?:\s*,\s*[^\s,]+)*\s+(.+)$/);
242
+ if (!declaration) throw new Error(`expected ${kind} targets and style properties`);
243
+ const allowed = kind === 'linkStyle' ? LINK_STYLE : NODE_STYLE;
244
+ for (const property of declaration[1].split(/(?<!\\),/)) {
245
+ const [, key, value] = property.match(/^\s*([\w-]+)\s*:\s*(\S.*?)\s*$/) ?? [];
246
+ if (!key) throw new Error(`invalid ${kind} property: ${property.trim()}`);
247
+ if (!allowed.has(key)) throw new Error(`${kind} property ${key} is forbidden`);
248
+ if (key === 'fill' && !/^(?:transparent|none)$/i.test(value)) {
249
+ throw new Error(`${kind} fill must be transparent or none`);
250
+ }
251
+ if (key === 'stroke') {
252
+ const hue = strokeHue(value);
253
+ if (hue !== undefined) accentStrokes.set(value.toLowerCase(), hue);
254
+ }
255
+ }
256
+ }
257
+
258
+ function lintableBody(lines) {
259
+ // Accessibility descriptions can contain whole lines that look like Mermaid statements.
260
+ return lines.join('\n')
261
+ .replace(/^[ \t]*accDescr\s*\{[^}]*\}/gm, (description) => description.replace(/[^\n]/g, ' '))
262
+ .replace(/^[ \t]*(?:%%|acc(?:Title|Descr)\s*:).*$/gm, '');
263
+ }
264
+
265
+ function checkMetadataLabels(body) {
266
+ // Pele calls metadata labels Markdown whether or not the value was double-quoted.
267
+ const unquoted = body.replace(QUOTED, '""');
268
+ for (const [, metadata] of unquoted.matchAll(/@\{([^{}]*)\}/g)) {
269
+ const label = metadata.match(/(?:^|[,\n])\s*label\s*:\s*([^,\n]*)/)?.[1];
270
+ rejectSemicolon('node label', withoutMermaidEntities(label ?? ''));
271
+ }
272
+ }
273
+
274
+ function sourceRules(source, extraType) {
275
+ const init = source.match(/%%\s*\{\s*(init|initialize)\b/i);
276
+ if (init) throw new Error(`${init[1]} directive is forbidden`);
277
+
278
+ const lines = source.split(/\r?\n/);
279
+ const opening = lines.findIndex((line) => line.trim());
280
+ const frontmatter = lines[opening] === '---';
281
+ const closing = frontmatter ? lines.indexOf('---', opening + 1) : -1;
282
+ if (frontmatter && closing === -1) throw new Error('expected frontmatter with closing ---');
283
+
284
+ const body = lines.slice(closing + 1);
285
+ const header = body.find((line) => line.trim() && !line.trimStart().startsWith('%%'));
286
+ const type = header?.trim().split(/[\s;]/)[0];
287
+ if (!TYPES.has(type) && (!type || type !== extraType)) {
288
+ throw new Error(`unsupported diagram type: ${type ?? '(empty)'}`);
289
+ }
290
+
291
+ const elk = checkFrontmatter(frontmatter ? lines.slice(opening + 1, closing) : [], type);
292
+ const lintable = lintableBody(body);
293
+ if (type === 'flowchart') checkMetadataLabels(lintable);
294
+
295
+ // Flowcharts accept semicolons both between statements and inside labels.
296
+ const flowLabels = /(?:--|-\.+|==)\s+.+?\s+(?:--+>|\.+->|==+>)|"(?:[^"\\]|\\.)*"|\[[^\]]*\]|\([^()]*\)|\{[^{}]*\}|\|[^|]*\|/g;
297
+ const accentStrokes = new Map();
298
+ for (const line of lintable.split('\n')) {
299
+ textBeforeParse(type, line.trim());
300
+ const statements = type === 'flowchart'
301
+ ? line.replace(flowLabels, (label) => label.replaceAll(';', '\u0000')).split(';')
302
+ : [line];
303
+ for (const statement of statements) {
304
+ const rule = statement.trim();
305
+ if (rule.startsWith('%%')) break;
306
+ if (/^rect(?=\s|$)/.test(rule)) throw new Error('rect statement is forbidden');
307
+ if (type === 'stateDiagram-v2' && /^[^:]*-\.->/.test(rule)) {
308
+ throw new Error('stateDiagram-v2 cannot use -.->; put status in the transition label');
309
+ }
310
+ const kind = rule.match(/^(classDef|style|linkStyle)(?=\s|$)/)?.[1];
311
+ if (!kind) continue;
312
+ if (kind === 'classDef' && NO_CLASSES.has(type)) throw new Error(`classDef is forbidden in ${type}`);
313
+ checkStyle(rule, kind, accentStrokes);
314
+ }
315
+ }
316
+ checkAccentHues([...accentStrokes.values()]);
317
+ return { type, elk, accentStrokes };
318
+ }
319
+
320
+ function overviewWarnings(type, model, dense, denseElk) {
321
+ if (type !== 'flowchart' || (model.direction !== 'TB' && !(dense && model.direction === 'LR'))) {
322
+ throw new Error('overview block 1 must be a flowchart TB unless a dense overview uses LR');
323
+ }
324
+ if (!denseElk && !model.subgraphs.length) throw new Error('overview block 1 must have at least one subgraph');
325
+
326
+ const warnings = [];
327
+ const subgraphIds = new Set(model.subgraphs.map((subgraph) => subgraph.id));
328
+ for (const subgraph of model.subgraphs) {
329
+ const direct = subgraph.nodes.filter((id) => !subgraphIds.has(id)).length;
330
+ if (direct > 5) warnings.push(`overview subgraph "${subgraph.title}" has ${direct} direct nodes; aim for about 5 per tier`);
331
+ }
332
+ for (const node of model.nodes.values()) {
333
+ if (subgraphIds.has(node.id)) continue;
334
+ const label = node.text?.trim() || node.id;
335
+ const words = label.replace(/\s*\(([^()]+)\)$/, (suffix, text) => STATUS_WORD.test(text) ? '' : suffix).split(/\s+/);
336
+ if (words.length > 3) warnings.push(`overview label "${label}" is long; use the name and at most one status word`);
337
+ }
338
+ return warnings;
339
+ }
340
+
341
+ function hasDashPattern(styles) {
342
+ return styles?.some((style) => /^stroke-dasharray\s*:/.test(style));
343
+ }
344
+
345
+ function checkDashedStatus(type, model) {
346
+ const dashed = new Set([...(model.classes?.values() ?? [])]
347
+ .filter(({ styles }) => hasDashPattern(styles))
348
+ .map(({ id }) => id));
349
+
350
+ function requireStatus({ id, text, classes, styles }, labelKind) {
351
+ const statusClass = classes.find((name) => dashed.has(name))
352
+ ?? (labelKind === 'node' && dashed.has('default') ? 'default' : undefined);
353
+ if (!statusClass && !hasDashPattern(styles)) return;
354
+ if (!STATUS_WORD.test((text || id).replace(/<[^>]*>/g, ' '))) {
355
+ const marker = statusClass ? `dashed class ${statusClass}` : 'dashed style';
356
+ throw new Error(`${marker} on ${id} requires a status word in the ${labelKind} label`);
357
+ }
358
+ }
359
+
360
+ const nodes = type === 'flowchart'
361
+ ? [...model.nodes.values()].filter(({ id }) => !model.subgraphLookup.has(id))
362
+ : [...model.entities.values()].map((entity) => ({
363
+ id: entity.label,
364
+ text: entity.alias || entity.label,
365
+ classes: entity.cssClasses.split(/\s+/),
366
+ styles: entity.cssStyles,
367
+ }));
368
+ for (const node of nodes) requireStatus(node, 'node');
369
+ for (const group of model.subgraphs) {
370
+ requireStatus({
371
+ id: group.id,
372
+ text: group.title,
373
+ classes: group.classes,
374
+ // Pele exposes flowchart subgraph styles on the node with the same ID.
375
+ styles: group.cssStyles ?? model.nodes?.get(group.id)?.styles,
376
+ }, 'subgraph');
377
+ }
378
+ }
379
+
380
+ function checkModel(type, model, overview, dense, denseElk) {
381
+ for (const field of ['accTitle', 'accDescr']) {
382
+ if (!model[field]?.trim()) throw new Error(`${field} is required`);
383
+ }
384
+
385
+ if (type === 'timeline' && model.periods.length > 4 && model.direction !== 'TD') {
386
+ throw new Error('use timeline TD for more than 4 periods');
387
+ }
388
+ const warnings = overview ? overviewWarnings(type, model, dense, denseElk) : [];
389
+ const counts = overview ? [] : [
390
+ [model.nodes?.size ?? model.states?.size ?? model.entities?.size, 9, 'nodes'],
391
+ [model.edges?.length ?? model.relations?.length ?? model.relationships?.length, 12, 'edges'],
392
+ [model.actors?.size, 5, 'participants'],
393
+ ];
394
+ for (const [count, limit, label] of counts) {
395
+ if (count > limit) warnings.push(`${count} ${label} exceeds ${limit}; consider splitting the view`);
396
+ }
397
+ const nodes = [...(model.nodes?.values() ?? [])];
398
+ if (model.boxes?.some((box) => box.fill !== 'transparent')) throw new Error('coloured box is forbidden');
399
+ if (type === 'flowchart' || type === 'erDiagram') checkDashedStatus(type, model);
400
+
401
+ const edges = model.edges ?? [];
402
+ if (type === 'flowchart') {
403
+ for (const node of nodes) {
404
+ if (node.labelType === 'text') rejectSemicolon('node label', node.text);
405
+ }
406
+ for (const edge of edges) {
407
+ if (edge.labelType === 'text') rejectSemicolon('edge label', edge.text);
408
+ }
409
+ for (const group of model.subgraphs) {
410
+ if (group.labelType === 'text') rejectSemicolon('subgraph label', group.title);
411
+ }
412
+ }
413
+
414
+ const nodeLabels = [
415
+ ...nodes.map((node) => node.text),
416
+ ...[...(model.states?.values() ?? [])].flatMap((state) => state.descriptions),
417
+ ...[...(model.entities?.values() ?? [])].map((entity) => entity.alias || entity.label),
418
+ ...(model.periods ?? []).flatMap((period) => [period.text, ...period.events]),
419
+ ];
420
+ const edgeLabels = [
421
+ ...edges.map((edge) => edge.text),
422
+ ...(model.relations ?? []).map((edge) => edge.relationTitle),
423
+ ...(model.relationships ?? []).map((edge) => edge.roleA),
424
+ ];
425
+ const actors = [...(model.actors?.values() ?? [])];
426
+ const aliases = actors.filter((actor) => actor.description !== actor.name).map((actor) => actor.description);
427
+ const messages = (model.messages ?? []).map((message) => message.message);
428
+
429
+ for (const [label, texts] of [
430
+ ['node label', nodeLabels],
431
+ ['edge label', edgeLabels],
432
+ ['participant alias', aliases],
433
+ ['sequence message', messages],
434
+ ]) {
435
+ for (const text of texts) {
436
+ if (!text) continue;
437
+ if (type !== 'flowchart') rejectSemicolon(label, text);
438
+ if (type === 'flowchart' && text.includes('*')) {
439
+ throw new Error(`asterisk in flowchart ${label}; use ✱`);
440
+ }
441
+ if (label === 'participant alias' && /[()[\]]/.test(text)) {
442
+ throw new Error('brackets or parentheses in participant alias; use a plain name and move status to message text');
443
+ }
444
+ }
445
+ }
446
+ const labels = [...nodeLabels, ...edgeLabels, ...actors.map((actor) => actor.description ?? actor.name)];
447
+ if (labels.some((label) => label?.length > 40)) warnings.push('label exceeds 40 characters; shorten it or split the view');
448
+ if (messages.some((message) => message?.length > 28)) {
449
+ warnings.push('sequence message exceeds 28 characters; shorten it or split the view');
450
+ }
451
+ return warnings;
452
+ }
453
+
454
+ function embeddedSvg(svg, accentStrokes) {
455
+ if (!accentStrokes.size) return svg;
456
+ // Rewrite only declared accent strokes. Keep neutral strokes, theme fallbacks and label text.
457
+ return svg.replace(/(<[^<>]*\sstyle=")([^"]*)"/g, (_, opening, style) =>
458
+ `${opening}${style.replace(/(^|;)stroke\s*:\s*([^;]+)/g, (declaration, separator, value) =>
459
+ accentStrokes.has(value.trim().toLowerCase()) ? `${separator}stroke:var(--_c)` : declaration)}"`);
460
+ }
461
+
462
+ async function main(args) {
463
+ if (args.length === 1 && args[0] === '--help') {
464
+ console.log(HELP);
465
+ return 0;
466
+ }
467
+ const options = optionsFor(args);
468
+ if (!options) {
469
+ console.error(HELP);
470
+ return 2;
471
+ }
472
+
473
+ let blocks;
474
+ try {
475
+ const source = await Bun.file(options.path).text();
476
+ blocks = /\.mmd$/i.test(options.path) ? [{ source, line: 1, firstLine: 1 }] : markdownBlocks(source);
477
+ if (!blocks.length && options.overview) throw new Error('overview block 1 is missing');
478
+ if (!blocks.length && options.expect) throw new Error('no Mermaid fences found');
479
+ } catch (error) {
480
+ console.error(`${options.path}: ${error.message}`);
481
+ return 1;
482
+ }
483
+ if (!blocks.length) {
484
+ console.log(`${options.path}: checked 0 Mermaid blocks`);
485
+ return 0;
486
+ }
487
+
488
+ let pele;
489
+ try {
490
+ pele = await loadRenderer(options.renderer);
491
+ } catch (error) {
492
+ const reason = error.code === 'ENOENT' ? `missing: ${options.renderer}` : error.message;
493
+ console.error(`Pele ${PELE_VERSION} renderer: ${reason}`);
494
+ return 3;
495
+ }
496
+
497
+ let failed = false;
498
+ const views = [];
499
+ for (const [index, block] of blocks.entries()) {
500
+ const number = index + 1;
501
+ const where = `${options.path} block ${number} (line ${block.line})`;
502
+ try {
503
+ const { type, elk, accentStrokes } = sourceRules(block.source, options.extraType);
504
+ const model = parseDiagram(pele, block.source, type);
505
+ const overview = options.overview && index === 0;
506
+ const dense = overview && type === 'flowchart' && model.edges.length > DENSE_OVERVIEW_EDGES;
507
+ const denseElk = dense && elk;
508
+ const warnings = checkModel(type, model, overview, dense, denseElk);
509
+ const digest = sha256(block.source);
510
+ const id = `mermaid-${number}-${digest.slice(0, 12)}`;
511
+ const { svg, width } = pele.render(block.source, { idPrefix: id });
512
+ const labelSize = NATURAL_LABEL_SIZE * (denseElk ? 1 : Math.min(1, TARGET_WIDTH / width));
513
+ if (labelSize < MIN_LABEL_SIZE) {
514
+ throw new Error(`label size ${labelSize.toFixed(3)}px is below ${MIN_LABEL_SIZE}px at ${TARGET_WIDTH}px; restructure the view`);
515
+ }
516
+ for (const warning of warnings) console.warn(`${where}: warning: ${warning}`);
517
+ const measurement = denseElk
518
+ ? `${DENSE_ELK_NOTE}; natural-size labels ${labelSize}px`
519
+ : `${elk ? 'default layout ' : ''}${width}px`;
520
+ views.push({ where, type, measurement, digest, id, svg, accentStrokes });
521
+ } catch (error) {
522
+ const location = error.line ? ` at line ${block.firstLine + error.line - 1}, column ${error.column}` : '';
523
+ const message = error instanceof pele.PeleError ? `Pele parse/render failure${location}: ${error.message}` : error.message;
524
+ console.error(`${where}: ${message}`);
525
+ failed = true;
526
+ }
527
+ }
528
+ if (failed) return 1;
529
+
530
+ try {
531
+ if (options.svgDir) mkdirSync(options.svgDir, { recursive: true });
532
+ for (const { where, type, measurement, digest, id, svg, accentStrokes } of views) {
533
+ let svgProof = '';
534
+ if (options.svgDir) {
535
+ const path = `${options.svgDir}/${id}.svg`;
536
+ const output = embeddedSvg(svg, accentStrokes);
537
+ await Bun.write(path, output);
538
+ svgProof = `; SVG sha256=${sha256(output)} ${path}`;
539
+ }
540
+ console.log(`${where}: ${type} ${measurement}; Pele ${PELE_VERSION}; source sha256=${digest}${svgProof}`);
541
+ }
542
+ } catch (error) {
543
+ console.error(`SVG output: ${error.message}`);
544
+ return 1;
545
+ }
546
+ return 0;
547
+ }
548
+
549
+ if (import.meta.main) process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,40 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kepano
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ The reset icon of the zoom controls is "rotate-ccw" from Lucide v1.14.0
26
+ (https://lucide.dev), under the ISC License:
27
+
28
+ Copyright (c) 2026 Lucide Icons and Contributors
29
+
30
+ Permission to use, copy, modify, and/or distribute this software for any
31
+ purpose with or without fee is hereby granted, provided that the above
32
+ copyright notice and this permission notice appear in all copies.
33
+
34
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
35
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
36
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
37
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
38
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
39
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
40
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
@@ -0,0 +1,8 @@
1
+ # Pele
2
+
3
+ - Upstream: [obsidianmd/pele](https://github.com/obsidianmd/pele)
4
+ - Distribution: [pele 1.13.0](https://registry.npmjs.org/pele/-/pele-1.13.0.tgz)
5
+ - npm integrity: `sha512-Ie8UKY9x00MsuR3jO6AzUwzK2Z6MIV3Tf4EDdITiuk8Uaz8K7g0R082WqsqNaSU8DdgkrRvZThzhit83mi/uiw==`
6
+ - `dist/pele.js` SHA-256: `37bea5005aa6d2dde929032ced5d2958cf642667cbc1fe675f9dfacf4ba15a51`
7
+ - Payload: unmodified `dist/pele.js` and `LICENSE` from the npm archive.
8
+ - Use: author-time Mermaid checks and static SVG export with Bun.