Repository navigation
Expand file tree
/
Copy pathcore.mjs
More file actions
1580 lines (1536 loc) · 119 KB
/
Copy pathcore.mjs
File metadata and controls
1580 lines (1536 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** Shared core: helpers, markdown + Mermaid parsers, layout, diagram styles + settings.
* Imported by index.html and 3d.html. Page-specific APIs (S, restyle, go, …) are attached via bindPage().
*/
'use strict';
/** @type {(s: string) => any} */
export const $=s=>document.querySelector(s);
/**
* Page-specific API (filled by each page after its render/player code exists).
* @type {{
* S: any,
* restyle: () => void,
* go: (i: number, fromPlay?: boolean) => void,
* toast: (m: string) => void,
* drawer: (o: boolean) => void,
* showErr: (m: string) => void,
* tryRender: () => void,
* encode: (str: string) => Promise<string>,
* }}
*/
export let page = /** @type {any} */ ({});
/** @param {typeof page} p */
export function bindPage(p){ page = p; }
/* ---------- shared core: helpers, markdown + Mermaid parsers, layout, diagram styles + settings ---------- */
/** @typedef {{id:string,label:string,shape:string,group:number|null,gx?:number,gy?:number,note?:string,icon?:string,iconFallback?:string,ci?:number,hk?:number,actor?:boolean,special?:string,kind?:string,members?:{f:string[],a:string[]},attrs?:string[],junction?:boolean,rank?:number,color?:string}} FxNode */
/** @typedef {FxNode & {gx:number,gy:number}} PlacedNode */
/** @typedef {{u:number,v:number,fw:boolean,bw:boolean,flip:boolean,a:number,b:number,chain:LayoutItem[],pts:number[][]}} Route */
/** @typedef {{real:boolean,i?:number,r:number,up:LayoutItem[],down:LayoutItem[],y:number,p?:number,bc?:number}} LayoutItem */
/** @typedef {{from:string,to:string,label:string,dotted:boolean,arrow:boolean,pts?:number[][]|null,route?:Route|null,an?:string,bn?:string}} FxLink */
/** @typedef {{title:string,icon?:string}} Group */
/** @typedef {{type:string,nodes:FxNode[],links:FxLink[],steps:Step[],groups:Group[],fixed?:boolean,noZones?:boolean,diagramTitle?:string,title?:string,intro?:string}} Graph */
/** @typedef {{title:string,intro:string,code:string,ordered:string[],named:Array<[string,string]>}} Scene */
/** @typedef {{docTitle:string,scenes:Scene[]}} MdDoc */
/** @param {unknown} s */
export const esc=s=>String(s).replace(/[&<>"]/g,c=>/** @type {Record<string,string>} */({'&':'&','<':'<','>':'>','"':'"'})[c]);
/** @param {string} s */
export const mdInline=s=>esc(s).replace(/\*\*(.+?)\*\*/g,'<b>$1</b>').replace(/`([^`]+)`/g,'<code>$1</code>');
/* ---------- markdown ---------- */
/** @param {string} md @returns {MdDoc} */
export function parseMarkdown(md){
const lines=md.replace(/\r/g,'').split('\n');
let docTitle='',heading='',para=/** @type {string[]} */([]),cur=/** @type {Scene|null} */(null);const scenes=/** @type {Scene[]} */([]);
for(let i=0;i<lines.length;i++){
const l=lines[i];/** @type {RegExpMatchArray|null} */let m;
if(m=l.match(/^\s*(```+|~~~+)\s*mermaid\s*$/i)){
/** @type {string[]} */ const code=[];i++;
while(i<lines.length&&!lines[i].trim().startsWith(m[1].slice(0,3))){code.push(lines[i]);i++}
cur=/** @type {Scene} */({title:heading||docTitle,intro:para.join(' '),code:code.join('\n'),ordered:[],named:[]});
scenes.push(cur);para=[];
}else if(m=l.match(/^(#{1,6})\s+(.*?)\s*#*$/)){
if(m[1].length===1&&!docTitle)docTitle=m[2];
heading=m[2];para=[];
}else if(cur&&(m=l.match(/^\s*\d+[.)]\s+(.*)/)))cur.ordered.push(m[1]);
else if(cur&&(m=l.match(/^\s*[-*+]\s+(.*)/))){
const k=m[1].match(/^(.+?)[::]\**\s+(.+)$/);
if(k)cur.named.push([k[1].replace(/[*`]/g,'').trim(),k[2].replace(/^\*+\s*/,'')]);
}else if(l.trim()&&!cur)para.push(l.trim());
else if(l.trim()&&cur&&!/^\s*([-*+]|\d+[.)])\s/.test(l)&&!/^\s*</.test(l)){/* trailing prose ignored */}
}
if(!scenes.length&&/^\s*(%%.*\n\s*)*(flowchart|graph|sequenceDiagram|stateDiagram|classDiagram|erDiagram|gantt|pie|mindmap|journey|timeline|quadrantChart|gitGraph|xychart(-beta)?|sankey(-beta)?|block(-beta)?|architecture(-beta)?|C4Context|C4Container|C4Component|C4Dynamic|C4Deployment|kanban|packet(-beta)?|requirementDiagram)\b/.test(md))
scenes.push({title:'',intro:'',code:md,ordered:[],named:[]});
return {docTitle,scenes};
}
/* ---------- mermaid: shared ---------- */
/** @param {string|null|undefined} t @returns {string} */
export function cleanText(t){
t=(t||'').trim();
if(/^".*"$/.test(t)||/^'.*'$/.test(t))t=t.slice(1,-1);
if(/^`.*`$/.test(t))t=t.slice(1,-1);
return t.replace(/<br\s*\/?>/gi,' ').replace(/<[^>]+>/g,'').replace(/#quot;/g,'"').replace(/#(\d+);/g,(_,/** @type {string} */n)=>String.fromCharCode(+n))
.replace(/\bfa[bsrl]?:fa-[\w-]+\s*/g,'').replace(/\*\*|__/g,'').replace(/\\n/g,' ').replace(/\s+/g,' ').trim();
}
/** @param {string} code */
export function codeLines(code){
let ls=code.split('\n').map(l=>l.replace(/%%.*$/,'').trim().replace(/;$/,''));
if(ls.find(l=>l)==='---'){const a=ls.indexOf('---'),b=ls.indexOf('---',a+1);if(b>a)ls=ls.slice(b+1)}
return ls.filter(l=>l);
}
/** @param {string} code @returns {Graph} */
export function parseMermaid(code){
const ls=codeLines(code);
if(!ls.length)throw new Error('The mermaid block is empty.');
if(/^(flowchart|graph)\b/i.test(ls[0]))return parseFlow(ls.slice(1));
if(/^sequenceDiagram\b/i.test(ls[0]))return parseSeq(ls.slice(1));
if(/^stateDiagram(-v2)?\b/i.test(ls[0]))return parseState(ls.slice(1));
if(/^classDiagram(-v2)?\b/i.test(ls[0]))return parseClass(ls.slice(1));
if(/^erDiagram\b/i.test(ls[0]))return parseER(ls.slice(1));
if(/^gantt\b/i.test(ls[0]))return parseGantt(ls.slice(1));
if(/^pie\b/i.test(ls[0]))return parsePie(ls[0],ls.slice(1));
if(/^mindmap\b/i.test(ls[0]))return parseMindmap(code);
if(/^journey\b/i.test(ls[0]))return parseJourney(ls.slice(1));
if(/^timeline\b/i.test(ls[0]))return parseTimeline(ls.slice(1));
if(/^quadrantChart\b/i.test(ls[0]))return parseQuadrant(ls.slice(1));
if(/^gitGraph\b/i.test(ls[0]))return parseGit(ls.slice(1));
if(/^xychart(-beta)?\b/i.test(ls[0]))return parseXY(ls.slice(1));
if(/^sankey(-beta)?\b/i.test(ls[0]))return parseSankey(ls.slice(1));
if(/^block(-beta)?\s*$/i.test(ls[0]))return parseBlock(ls.slice(1));
if(/^architecture(-beta)?\b/i.test(ls[0]))return parseArch(ls.slice(1));
if(/^C4(Context|Container|Component|Dynamic|Deployment)\b/.test(ls[0]))return parseC4(ls[0],ls.slice(1));
if(/^kanban\b/i.test(ls[0]))return parseKanban(code);
if(/^packet(-beta)?\b/i.test(ls[0]))return parsePacket(ls.slice(1));
if(/^requirementDiagram\b/i.test(ls[0]))return parseReq(ls.slice(1));
if(/^radar(-beta)?\b/i.test(ls[0]))return parseRadar(ls.slice(1));
if(/^treemap(-beta)?\b/i.test(ls[0]))return parseTreemap(code);
if(/^zenuml\b/i.test(ls[0]))return parseZen(ls.slice(1));
throw new Error('“'+ls[0].split(/\s/)[0]+'” diagrams are not supported yet. This version reads flowchart, sequenceDiagram, stateDiagram, classDiagram, erDiagram, gantt, pie, mindmap, journey, timeline, quadrantChart, gitGraph, xychart, sankey, block, architecture, C4, kanban, packet, requirementDiagram, radar, treemap and zenuml.');
}
/* ---------- mermaid: flowchart ---------- */
export const ID_RE=/^[\wÀ-]+(?:[-.][\wÀ-]+)*/;
/** @type {Array<[string,string|null,string]>} */
export const SHAPES=[['(((',')))','circle'],['([','])','pill'],['[[',']]','box'],['[(',')]','cyl'],['((','))','circle'],['{{','}}','hex'],['[/',null,'box'],['[\\',null,'box'],['[',']','box'],['(',')','pill'],['{','}','hex'],['>',']','box']];
/** @type {Record<string,string>} */
export const SHAPE_ALIAS={cyl:'cyl',cylinder:'cyl',database:'cyl',db:'cyl',diamond:'hex',diam:'hex',decision:'hex',hex:'hex',hexagon:'hex',circle:'circle',circ:'circle','sm-circ':'circle',stadium:'pill',pill:'pill',rounded:'pill',terminal:'pill'};
/** @param {string[]} ls @returns {Graph} */
export function parseFlow(ls){
const nodes=/** @type {Map<string,FxNode>} */(new Map()),links=/** @type {FxLink[]} */([]),groups=/** @type {Group[]} */([]),stack=/** @type {number[]} */([]);
/** @param {string} id @returns {FxNode} */
const getNode=id=>{
if(!nodes.has(id))nodes.set(id,{id,label:id,shape:'box',group:null});
const n=/** @type {FxNode} */(nodes.get(id));if(n.group==null&&stack.length)n.group=stack[stack.length-1];return n;
};
for(const line of ls){
/** @type {RegExpMatchArray|null} */ let m;
if(/^(classDef|class|style|linkStyle|click|direction|accTitle|accDescr)\b/.test(line))continue;
if(m=line.match(/^subgraph\s+(.*)$/)){
const rest=m[1].trim();const t=rest.match(/^[\w-]+\s*\[(.+)\]$/);
groups.push({title:cleanText(t?t[1]:rest)});stack.push(groups.length-1);continue;
}
if(line==='end'){stack.pop();continue}
statement(line);
}
/** @param {string} s */
function statement(s){
let pos=0;
const ws=()=>{while(s[pos]===' '||s[pos]==='\t')pos++};
const nodeRef=()=>{
ws();const m=s.slice(pos).match(ID_RE);if(!m)return null;
pos+=m[0].length;const n=getNode(m[0]);const rest=s.slice(pos);
if(rest.startsWith('@{')){
const e=rest.indexOf('}');
if(e>0){const body=rest.slice(2,e);const lm=body.match(/label:\s*(?:"([^"]*)"|([^,]+))/);const sm=body.match(/shape:\s*([\w-]+)/);
if(lm)n.label=cleanText(lm[1]??lm[2]);if(sm)n.shape=SHAPE_ALIAS[sm[1]]||'box';pos+=e+1}
}else for(const [o,c,shape] of SHAPES){
if(!rest.startsWith(o))continue;
let i=o.length,found=-1,clen=0;
for(;i<rest.length;i++){
if(rest[i]==='"'){const q=rest.indexOf('"',i+1);if(q<0)break;i=q;continue}
if(c?rest.startsWith(c,i):(rest.startsWith('/]',i)||rest.startsWith('\\]',i))){found=i;clen=c?c.length:2;break}
}
if(found>=0){n.label=cleanText(rest.slice(o.length,found))||n.id;n.shape=shape;pos+=found+clen}
break;
}
const cm=s.slice(pos).match(/^:::[\w-]+/);if(cm)pos+=cm[0].length;
return n;
};
const nodeGroup=()=>{
let n=nodeRef();if(!n)return null;const arr=[n];
for(;;){ws();if(s[pos]!=='&')break;pos++;n=nodeRef();if(!n)break;arr.push(n)}
return arr;
};
const edgeTok=()=>{
ws();const r=s.slice(pos);let label='',tok;/** @type {RegExpMatchArray|null} */let m;
if(m=r.match(/^<?(-{2,}>|-{3,}|-{2,}[ox](?=\s)|={2,}>|={3,}|-\.+->?|~{3,})/)){tok=m[0];pos+=m[0].length}
else if(m=r.match(/^<?(--|==|-\.)(?![-=>.])\s*(.+?)\s*(\.+-+>?|={2,}>?|-{2,}>?)(?=\s|$|[\w("'[])/)){tok=m[1]+m[3];label=m[2];pos+=m[0].length}
else return null;
ws();const lm=s.slice(pos).match(/^\|([^|]*)\|/);if(lm){label=lm[1];pos+=lm[0].length}
return {label:cleanText(label),dotted:tok.includes('.'),arrow:tok.endsWith('>')};
};
let left=nodeGroup();if(!left)return;
for(;;){
const e=edgeTok();if(!e)break;const right=nodeGroup();if(!right)break;
for(const a of left)for(const b of right)links.push({from:a.id,to:b.id,label:e.label,dotted:e.dotted,arrow:e.arrow});
left=right;
}
}
const N=[...nodes.values()];if(!N.length)throw new Error('No boxes found in the flowchart.');
const by=(/** @type {string} */id)=>/** @type {FxNode} */(nodes.get(id));
/** @type {Step[]} */
const steps=links.map((l,i)=>{
const a=by(l.from),b=by(l.to);
if(a===b)return {kind:'node',nodes:[a.id],title:a.label,auto:l.label||('**'+a.label+'** repeats.')};
let auto;
if(l.label)auto=a.shape==='hex'?'If the answer is **'+l.label+'**, continue to **'+b.label+'**.':'**'+a.label+'** → **'+b.label+'**: '+l.label+'.';
else auto='**'+a.label+'** hands over to **'+b.label+'**.';
return {kind:'edge',link:i,reverse:false,from:a.id,to:b.id,nodes:[a.id,b.id],title:a.label+' → '+b.label,chip:l.label,auto};
});
return {type:'flow',nodes:N,links,steps,groups};
}
/* ---------- mermaid: sequence ---------- */
/** @param {string[]} ls @returns {Graph} */
export function parseSeq(ls){
const nodes=/** @type {Map<string,FxNode>} */(new Map()),links=/** @type {FxLink[]} */([]),lmap=/** @type {Map<string,number>} */(new Map()),steps=/** @type {Step[]} */([]),ctx=/** @type {Array<{text:string|null}>} */([]);
/** @type {Record<string,string>} */
const WORD={alt:'When',else:'Otherwise',opt:'Optional',loop:'Repeat',par:'In parallel',and:'In parallel',critical:'Critical',break:'Stop if',option:'Otherwise'};
/** @param {string} id @param {string} [label] @param {boolean} [actor] @returns {FxNode} */
const getNode=(id,label,actor)=>{
id=id.trim();
if(!nodes.has(id)){const lb=cleanText(label||id);nodes.set(id,{id,label:lb,shape:actor?'pill':(/\b(db|database|sql|mysql|postgres|redis|cache|storage|store|s3)\b|資料庫/i.test(lb)?'cyl':'box'),group:null,actor:!!actor})}
return /** @type {FxNode} */(nodes.get(id));
};
const tag=()=>{for(let i=ctx.length-1;i>=0;i--)if(ctx[i].text!=null)return /** @type {string} */(ctx[i].text);return ''};
for(const line of ls){
let m;
if(m=line.match(/^(?:create\s+)?(participant|actor)\s+(.+?)(?:\s+as\s+(.+))?$/i)){getNode(m[2],m[3],/actor/i.test(m[1]));continue}
if(m=line.match(/^(alt|opt|loop|par|critical|break|rect|box)\b\s*(.*)$/i)){
const k=m[1].toLowerCase();ctx.push({text:(k==='rect'||k==='box')?null:(WORD[k]+(m[2]?': '+cleanText(m[2]):''))});continue}
if(m=line.match(/^(else|and|option)\b\s*(.*)$/i)){if(ctx.length)ctx[ctx.length-1].text=WORD[m[1].toLowerCase()]+(m[2]?': '+cleanText(m[2]):'');continue}
if(/^end$/i.test(line)){ctx.pop();continue}
if(m=line.match(/^note\s+(?:over|left of|right of)\s+([^:]+):\s*(.*)$/i)){
const ids=m[1].split(',').map(s=>getNode(s).id);
steps.push({kind:'node',nodes:ids,title:'Note',auto:cleanText(m[2]),tag:tag()});continue}
if(m=line.match(/^(.+?)\s*(<<-->>|<<->>|-->>|->>|--x|-x|--\)|-\)|-->|->)\s*[+-]?\s*(.+?)\s*:\s*(.*)$/)){
const a=getNode(m[1]),b=getNode(m[3]),text=cleanText(m[4]),dotted=m[2].startsWith('--')||m[2].startsWith('<<--');
if(a===b){steps.push({kind:'node',nodes:[a.id],title:text||a.label,auto:'**'+a.label+'** does this on its own.',tag:tag()});continue}
const key=[a.id,b.id].sort().join('\u0001');let li=lmap.get(key);
if(li==null){li=links.length;lmap.set(key,li);links.push({from:a.id,to:b.id,label:'',dotted:false,arrow:false})}
steps.push({kind:'edge',link:li,reverse:links[li].from!==a.id,from:a.id,to:b.id,nodes:[a.id,b.id],title:text||(a.label+' → '+b.label),
auto:'**'+a.label+'** '+(dotted?'replies to':'sends this to')+' **'+b.label+'**.',tag:tag()});
}
}
const N=[...nodes.values()];if(!N.length)throw new Error('No participants found in the sequence diagram.');
return {type:'seq',nodes:N,links,steps,groups:[]};
}
/* ---------- mermaid: shared helpers for the other diagram types ---------- */
/** @typedef {{kind:string,nodes:string[],title:string,auto:string,tag?:string,chip?:string,link?:number,reverse?:boolean,from?:string,to?:string,text?:string,custom?:boolean}} Step */
/** @typedef {{label?:string,dotted?:boolean,arrow?:boolean}} LinkOpts */
/** @typedef {{auto:string,title?:string,chip?:string,tag?:string}} StepOpts */
/** @param {string} s */
export const ucWords=s=>/[a-z]/.test(s)||!/[A-Z]/.test(s)?s:s.toLowerCase().replace(/[_-]+/g,' ').replace(/^\w/,c=>c.toUpperCase());
export function graphKit(){
const nodes=/** @type {Map<string,FxNode>} */(new Map()),links=/** @type {FxLink[]} */([]),groups=/** @type {Group[]} */([]),stack=/** @type {number[]} */([]);
/** @param {string} id @param {string|null} [label] @param {string} [shape] @returns {FxNode} */
const node=(id,label,shape)=>{
if(!nodes.has(id))nodes.set(id,{id,label:label||id,shape:shape||'box',group:stack.length?stack[stack.length-1]:null});
return /** @type {FxNode} */(nodes.get(id));
};
/** @param {FxNode} a @param {FxNode} b @param {LinkOpts} [o] */
const link=(a,b,o={})=>{links.push({from:a.id,to:b.id,label:o.label||'',dotted:!!o.dotted,arrow:!!o.arrow});return links.length-1};
/** @param {number} li @param {StepOpts} o @returns {Step} */
const edgeStep=(li,o)=>{const l=links[li],a=/** @type {FxNode} */(nodes.get(l.from)),b=/** @type {FxNode} */(nodes.get(l.to));
return {kind:'edge',link:li,reverse:false,from:a.id,to:b.id,nodes:[a.id,b.id],title:o.title||(a.label+' → '+b.label),chip:o.chip||'',auto:o.auto,tag:o.tag||''}};
/** @param {FxNode} n @param {StepOpts} o @returns {Step} */
const nodeStep=(n,o)=>({kind:'node',nodes:[n.id],title:o.title||n.label,auto:o.auto,tag:o.tag||''});
/** @param {FxNode} n @param {string} t */
const addNote=(n,t)=>{
t=cleanText(t);if(t)n.note=n.note?n.note+' '+t:t};
return {nodes,links,groups,stack,node,link,edgeStep,nodeStep,addNote};
}
/* ---------- mermaid: state ---------- */
/** @param {string[]} ls @returns {Graph} */
export function parseState(ls){
const K=graphKit(),steps=/** @type {Step[]} */([]),comp=/** @type {string[]} */([]),trs=/** @type {Array<{li:number,label:string,tag:string}>} */([]);
const B=(/** @type {string} */s)=>'**'+s+'**';
/** @param {string} raw */
const ref=raw=>{
raw=raw.trim().replace(/:::[\w-]+$/,'');
if(raw==='[*]')return null;
return K.node(raw,raw);
};
const ends=/** @type {Map<string,FxNode>} */(new Map());
/** @param {string} kind @returns {FxNode} */
const special=(kind)=>{
const g=K.stack.length?K.stack[K.stack.length-1]:'root',key=kind+'_'+g;
if(!ends.has(key)){const inner=g!=='root';const n=K.node('__'+key,kind==='start'?(inner?'Start ('+K.groups[g].title+')':'Start'):(inner?'Done ('+K.groups[g].title+')':'End'),'circle');n.special=kind;n.icon=kind==='start'?'🟢':'🏁';ends.set(key,n)}
return /** @type {FxNode} */(ends.get(key));
};
for(let i=0;i<ls.length;i++){
const line=ls[i];/** @type {RegExpMatchArray|null} */let m;
if(/^(classDef|class|style|direction|accTitle|accDescr|hide|scale)\b/.test(line)||line==='--'||line==='||')continue;
if(m=line.match(/^note\s+(?:left|right)\s+of\s+([^:]+?)\s*:\s*(.+)$/i)){K.addNote(K.node(m[1].trim()),m[2]);continue}
if(m=line.match(/^note\s+(?:left|right)\s+of\s+(.+)$/i)){const n=K.node(m[1].trim()),t=[];i++;while(i<ls.length&&!/^end\s*note$/i.test(ls[i])){t.push(ls[i]);i++}K.addNote(n,t.join(' '));continue}
if(m=line.match(/^state\s+"([^"]+)"\s+as\s+([\w-]+)\s*(\{)?$/)){const n=K.node(m[2]);n.label=cleanText(m[1]);if(m[3]){K.groups.push({title:n.label});K.stack.push(K.groups.length-1);comp.push(m[2])}continue}
if(m=line.match(/^state\s+([\w-]+)\s*<<(choice|fork|join)>>$/i)){const n=K.node(m[1]);n.shape=m[2].toLowerCase()==='choice'?'hex':'pill';n.label=m[2].toLowerCase()==='choice'?'Check':(m[2].toLowerCase()==='fork'?'Split':'Join');continue}
if(m=line.match(/^state\s+([\w-]+)\s*\{$/)){K.groups.push({title:cleanText(m[1])});K.stack.push(K.groups.length-1);comp.push(m[1]);continue}
if(m=line.match(/^state\s+([\w-]+)$/)){K.node(m[1]);continue}
if(line==='}'){K.stack.pop();comp.pop();continue}
if(m=line.match(/^(\[\*\]|[\w-]+(?::::[\w-]+)?)\s*-->\s*(\[\*\]|[\w-]+(?::::[\w-]+)?)\s*(?::\s*(.*))?$/)){
const a=ref(m[1])||special('start'),b=ref(m[2])||special('end'),label=cleanText(m[3]||'');
trs.push({li:K.link(a,b,{label,arrow:true}),label,tag:K.stack.length?K.groups[K.stack[K.stack.length-1]].title:''});
continue;
}
if(m=line.match(/^([\w-]+)\s*:\s*(.+)$/)){K.addNote(K.node(m[1]),m[2]);continue}
if(m=line.match(/^([\w-]+)$/)){K.node(m[1]);continue}
}
const N=[...K.nodes.values()];if(!N.length)throw new Error('No states found in the state diagram.');
N.forEach(n=>{if(!n.special&&n.label===n.id)n.label=ucWords(n.label)});
for(const {li,label,tag} of trs){
const l=K.links[li],a=/** @type {FxNode} */(K.nodes.get(l.from)),b=/** @type {FxNode} */(K.nodes.get(l.to));let auto;
if(a.special==='start')
auto=tag?'Inside '+B(tag)+', it starts in '+B(b.label)+'.':'It all starts in '+B(b.label)+'.';
else if(b.special==='end')auto=B(a.label)+' is where it finishes'+(label?' — when '+label:'')+'.';
else if(a.shape==='hex')auto=label?'If '+label+', it goes to '+B(b.label)+'.':'The check sends it to '+B(b.label)+'.';
else auto=label?'When '+B(label)+' happens, '+B(a.label)+' changes to '+B(b.label)+'.':B(a.label)+' moves on to '+B(b.label)+'.';
steps.push(K.edgeStep(li,{auto,chip:label,tag,title:a.special?'Start → '+b.label:b.special?a.label+' → End':a.label+' → '+b.label}));
}
return {type:'state',nodes:N,links:K.links,steps,groups:K.groups};
}
/* ---------- mermaid: class ---------- */
/** @type {Array<[string,string,number,number,string?]>} */
export const CLASS_REL=[
['<|--','is a kind of',1,0],['--|>','is a kind of',0,0],['<|..','is a way of doing',1,1],['..|>','is a way of doing',0,1],
['*--','is made up of',0,0,'contains'],['--*','is part of',0,0],['o--','has',0,0],['--o','belongs to',0,0],
['<-->','works with',0,0],['-->','uses',0,0],['<--','uses',1,0],['..>','depends on',0,1],['<..','depends on',1,1],['--','is linked to',0,0],['..','is loosely linked to',0,1]
];
/** @param {string[]} ls @returns {Graph} */
export function parseClass(ls){
const K=graphKit(),steps=/** @type {Step[]} */([]),rels=/** @type {RegExpMatchArray[]} */([]);
/** @param {string} raw */
const cls=raw=>{
let id=raw.trim().replace(/:::[\w-]+$/,''),label=/** @type {string|null} */(null);/** @type {RegExpMatchArray|null} */let m;
if(m=id.match(/^([\w.-]+)\s*\["?([^"\]]*)"?\]$/)){id=m[1];label=cleanText(m[2])}
if(m=id.match(/^`(.+)`$/))id=m[1];
const base=id.replace(/~[^~]*~/g,''),n=K.node(base,base);
if(label)n.label=label;
const g=id.match(/~([^~]+)~/);if(g&&n.label===base)n.label=base+'<'+g[1]+'>';
n.iconFallback='🧩';
return n;
};
/** @param {FxNode} n @param {string} t */
const member=(n,t)=>{t=t.trim();if(!t)return;/** @type {RegExpMatchArray|null} */let m;
if(m=t.match(/^<<(.+)>>$/)){n.kind=cleanText(m[1]);return}
t=t.replace(/[$*]$/,'').replace(/^[+\-#~]/,'').trim();
(n.members=n.members||{f:[],a:[]})[/\(/.test(t)?'a':'f'].push(t.replace(/\s+/g,' '));
};
const relRe=new RegExp('^(\\S+?)\\s*(?:"([^"]*)"\\s*)?('+CLASS_REL.map(r=>String(r[0]).replace(/[|*.]/g,'\\$&')).join('|')+')\\s*(?:"([^"]*)"\\s*)?(\\S+?)\\s*(?::\\s*(.*))?$');
for(let i=0;i<ls.length;i++){
const line=ls[i];let m;
if(/^(classDef|cssClass|style|direction|accTitle|accDescr|click|callback|link)\b/.test(line))continue;
if(m=line.match(/^namespace\s+([\w.-]+)\s*\{$/)){K.groups.push({title:m[1]});K.stack.push(K.groups.length-1);continue}
if(m=line.match(/^class\s+(.+?)\s*\{\s*(.*?)\s*(\})?$/)){const n=cls(m[1]);if(m[2])member(n,m[2]);if(!m[3]){i++;while(i<ls.length&&ls[i]!=='}'){member(n,ls[i]);i++}}continue}
if(m=line.match(/^class\s+(.+)$/)){cls(m[1]);continue}
if(line==='}'){K.stack.pop();continue}
if(m=line.match(/^<<(.+)>>\s+([\w.-]+)$/)){cls(m[2]).kind=cleanText(m[1]);continue}
if(m=line.match(/^note\s+for\s+([\w.-]+)\s+"(.*)"$/)){K.addNote(cls(m[1]),m[2].replace(/\\n/g,' '));continue}
if(/^note\s/.test(line))continue;
if(m=line.match(relRe)){rels.push(m);continue}
if(m=line.match(/^([\w.-]+)\s*:\s*(.+)$/)){member(cls(m[1]),m[2]);continue}
}
/** @param {string|undefined} s */
const card=s=>{s=(s||'').trim();return /** @type {Record<string,string>} */({'1':'one','0..1':'zero or one','1..*':'one or more','*':'many','n':'many','0..n':'zero or more','0..*':'zero or more','1..n':'one or more','many':'many'})[s]||s};
for(const m of rels){
const r=/** @type {[string,string,number,number,string?]} */(CLASS_REL.find(x=>x[0]===m[3]));const a=cls(m[1]),b=cls(m[5]);
const label=cleanText(m[6]||'');
const li=K.link(a,b,{label,dotted:!!r[3],arrow:/>|\|>/.test(m[3])&&!/^</.test(m[3])});
const [s,o]=r[2]?[b,a]:[a,b],B=(/** @type {FxNode} */x)=>'**'+x.label+'**';
let auto=label?B(s)+' '+label+' '+B(o)+' ('+(r[4]||r[1])+').':B(s)+' '+r[1]+' '+B(o)+'.';
if(r[1]==='is a kind of')auto=B(s)+' is a kind of '+B(o)+', so it gets everything '+o.label+' has.'+(label?' ('+label+')':'');
if(r[1]==='is a way of doing')auto=B(s)+' follows the rules set by '+B(o)+'.'+(label?' ('+label+')':'');
const c1=card(m[2]),c2=card(m[4]),chip=(c1||c2)?(c1||'?')+' → '+(c2||'?'):label;
if(c1||c2)auto+=' '+(c1?'One side: '+c1+' '+a.label+'.':'')+(c2?' Other side: '+c2+' '+b.label+'.':'');
steps.push(K.edgeStep(li,{auto:auto.trim(),chip}));
}
const N=[...K.nodes.values()];if(!N.length)throw new Error('No classes found in the class diagram.');
N.forEach(n=>{
const p=[];if(n.kind)p.push('Type: '+n.kind+'.');
if(n.members){if(n.members.f.length)p.push('Holds: '+n.members.f.join(', ')+'.');if(n.members.a.length)p.push('Can do: '+n.members.a.join(', ')+'.')}
if(p.length)n.note=p.join(' ')+(n.note?' '+n.note:'');
});
if(!steps.length)N.forEach(n=>steps.push(K.nodeStep(n,{auto:n.note||('This is **'+n.label+'**.')})));
return {type:'class',nodes:N,links:K.links,steps,groups:K.groups};
}
/* ---------- mermaid: ER ---------- */
/** @type {Record<string,string>} */
export const ER_CARD={'||':'exactly one','|o':'zero or one','o|':'zero or one','}|':'one or more','|{':'one or more','}o':'zero or more','o{':'zero or more'};
/** @param {string[]} ls @returns {Graph} */
export function parseER(ls){
const K=graphKit(),steps=/** @type {Step[]} */([]);
/** @param {string} raw */
const ent=raw=>{
raw=raw.trim();/** @type {RegExpMatchArray|null} */let m;let id=raw,label=/** @type {string|null} */(null);
if(m=raw.match(/^([\w-]+)\s*\[\s*"?([^"\]]*)"?\s*\]$/)){id=m[1];label=m[2]}
else if(m=raw.match(/^"(.+)"$/))id=m[1];
const n=K.node(id,label?cleanText(label):ucWords(id));n.iconFallback='📋';return n;
};
/** @param {FxNode} n @param {string} t */
const attr=(n,t)=>{const m=t.trim().match(/^(\S+)\s+(\S+)((?:\s+(?:PK|FK|UK)\s*,?)*)\s*(?:"(.*)")?$/);if(!m)return;
const keys=m[3]||'',extra=/PK/.test(keys)?' (ID)':/FK/.test(keys)?' (link)':'';(n.attrs=n.attrs||[]).push(m[2].replace(/_/g,' ')+extra+(m[4]?' — '+m[4]:''))};
for(let i=0;i<ls.length;i++){
const line=ls[i];let m;
if(/^(classDef|class|style|direction|accTitle|accDescr)\b/.test(line))continue;
if(m=line.match(/^(.+?)\s*(\|o|\|\||\}o|\}\|)(--|\.\.)(o\||\|\||o\{|\|\{)\s*(.+?)\s*:\s*(.+)$/)){
const a=ent(m[1]),b=ent(m[5]),label=cleanText(m[6]),cl=ER_CARD[m[2]],cr=ER_CARD[m[4]];
const li=K.link(a,b,{label,dotted:m[3]==='..'});
const one=(/** @type {FxNode} */x)=>x.label.toLowerCase();
steps.push(K.edgeStep(li,{chip:label,auto:'Each **'+a.label+'** '+label+' **'+cr+'** '+one(b)+'. Each '+one(b)+' is linked to **'+cl+'** '+one(a)+'.'}));
continue;
}
if(m=line.match(/^(.+?)\s*\{\s*(.*?)\s*(\})?$/)){const n=ent(m[1]);if(m[2])attr(n,m[2]);if(!m[3]){i++;while(i<ls.length&&ls[i]!=='}'){attr(n,ls[i]);i++}}continue}
if(m=line.match(/^("[^"]+"|[\w-]+(?:\s*\[[^\]]*\])?)$/))ent(m[1]);
}
const N=[...K.nodes.values()];if(!N.length)throw new Error('No tables found in the ER diagram.');
N.forEach(n=>{if(n.attrs)n.note='Stores: '+n.attrs.join(', ')+'.'});
if(!steps.length)N.forEach(n=>steps.push(K.nodeStep(n,{auto:n.note||('This is **'+n.label+'**.')})));
return {type:'er',nodes:N,links:K.links,steps,groups:[]};
}
/* ---------- mermaid: gantt ---------- */
/** @typedef {{label:string,id:string,start:string|null,end:string|null,tags:string[],section:number|null,deps:GanttTask[],s:number|null,e:number|null,d:number|null,soft?:boolean,n:FxNode}} GanttTask */
/** @param {string[]} ls @returns {Graph} */
export function parseGantt(ls){
const K=graphKit(),tasks=/** @type {GanttTask[]} */([]);let title='',fmt='YYYY-MM-DD',section=/** @type {number|null} */(null);
const DAY=864e5,UNIT=/** @type {Record<string,number>} */({ms:1,s:1e3,m:6e4,h:36e5,d:DAY,w:7*DAY,M:30*DAY,y:365*DAY});
/** @param {string} s @returns {number|null} */
const parseDate=s=>{s=s.trim();/** @type {RegExpMatchArray|null} */let m;
if(/^YYYY-MM-DD/.test(fmt)&&(m=s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{2}))?$/)))return Date.UTC(+m[1],+m[2]-1,+m[3],+(m[4]||0),+(m[5]||0));
if(/^DD[-/.]MM[-/.]YYYY/.test(fmt)&&(m=s.match(/^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/)))return Date.UTC(+m[3],+m[2]-1,+m[1]);
if(/^MM[-/.]DD[-/.]YYYY/.test(fmt)&&(m=s.match(/^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/)))return Date.UTC(+m[3],+m[1]-1,+m[2]);
if(/^\d{4}-\d{2}-\d{2}/.test(s)){const t=Date.parse(s);if(!isNaN(t))return t}
return null};
/** @param {string} s */
const dur=s=>{const m=s.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w|M|y)$/);return m?+m[1]*UNIT[m[2]]:null};
for(const line of ls){
let m;
if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue}
if(m=line.match(/^dateFormat\s+(.+)$/)){fmt=m[1].trim();continue}
if(/^(axisFormat|tickInterval|excludes|includes|todayMarker|weekday|inclusiveEndDates|topAxis|displayMode|accTitle|accDescr|click)\b/.test(line))continue;
if(m=line.match(/^section\s+(.+)$/)){K.groups.push({title:cleanText(m[1])});section=K.groups.length-1;continue}
if(m=line.match(/^(.+?)\s*:\s*(.*)$/)){
const parts=m[2].split(',').map(s=>s.trim()).filter(Boolean),tags=/** @type {string[]} */([]);
while(parts.length&&/^(done|active|crit|milestone|vert)$/.test(parts[0]))tags.push(/** @type {string} */(parts.shift()));
let id=/** @type {string|null} */(null),start=/** @type {string|null} */(null),end=/** @type {string|null} */(null);
if(parts.length>=3)[id,start,end]=parts;
else if(parts.length===2){if(parseDate(parts[0])!=null||/^after\s/.test(parts[0]))[start,end]=parts;else[id,end]=parts}
else if(parts.length===1)end=parts[0];
tasks.push(/** @type {GanttTask} */({label:cleanText(m[1]),id:id||('task'+(tasks.length+1)),start,end,tags,section}));
}
}
if(!tasks.length)throw new Error('No tasks found in the gantt chart.');
const byId=/** @type {Map<string,GanttTask>} */(new Map());tasks.forEach(t=>byId.set(t.id,t));
let prev=/** @type {GanttTask|null} */(null);
tasks.forEach(t=>{
t.deps=[];
if(t.start&&/^after\s/.test(t.start)){t.deps=/** @type {GanttTask[]} */(t.start.replace(/^after\s+/,'').split(/\s+/).map(x=>byId.get(x)).filter(Boolean));t.s=t.deps.length&&t.deps.every(d=>d.e!=null)?Math.max(...t.deps.map(d=>/** @type {number} */(d.e))):null}
else if(t.start){t.s=parseDate(t.start)}
else{if(prev)t.deps=[prev];t.s=prev?prev.e:null}
const d=t.end?dur(t.end):null,ed=t.end?parseDate(t.end):null,un=t.end&&t.end.match(/^until\s+(\S+)/);
if(t.tags.includes('milestone'))t.e=t.s;
else if(d!=null&&t.s!=null)t.e=t.s+d;
else if(ed!=null)t.e=ed;
else if(un&&byId.get(un[1])&&/** @type {GanttTask} */(byId.get(un[1])).s!=null)t.e=/** @type {GanttTask} */(byId.get(un[1])).s;
else t.e=null;
t.d=d;prev=t;
});
tasks.forEach(t=>{
if(t.start&&!/^after\s/.test(t.start)&&t.s!=null&&!t.deps.length){
let best=/** @type {GanttTask|null} */(null);tasks.forEach(o=>{if(o!==t&&o.e!=null&&o.e<=/** @type {number} */(t.s)&&
tasks.indexOf(o)<tasks.indexOf(t)&&(!best||o.e>/** @type {number} */(best.e)))best=o});
if(best){t.deps=[best];t.soft=true}
}
});
/** @param {number} ms */
const fd=ms=>{const d=new Date(ms);return d.getUTCDate()+' '+['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getUTCMonth()]+' '+d.getUTCFullYear()};
/** @param {number} ms */
const fdur=ms=>{const dd=ms/DAY;if(dd>=1){const w=dd/7;return Number.isInteger(w)&&w>1?w+' weeks':(Math.round(dd*10)/10)+(dd===1?' day':' days')}const h=ms/36e5;return h>=1?Math.round(h*10)/10+' hours':Math.round(ms/6e4)+' minutes'};
tasks.forEach(t=>{const n=K.node(t.id,t.label,t.tags.includes('milestone')?'circle':'box');n.group=t.section;
if(t.tags.includes('milestone'))n.icon='🚩';else if(t.tags.includes('done'))n.icon='✅';else if(t.tags.includes('active'))n.icon='⏳';else if(t.tags.includes('crit'))n.icon='❗';
t.n=n});
const order=tasks.slice().sort((a,b)=>(a.s??Infinity)-(b.s??Infinity)||tasks.indexOf(a)-tasks.indexOf(b));
const steps=/** @type {Step[]} */([]),B=(/** @type {string} */s)=>'**'+s+'**';
order.forEach(t=>{
const lis=t.deps.map(d=>K.link(d.n,t.n,{arrow:true,dotted:!!t.soft}));
const ms=t.tags.includes('milestone'),when=t.s!=null?(ms?'is reached on '+B(fd(t.s)):'starts on '+B(fd(t.s))):'';
let auto;
if(t.deps.length&&!t.soft)auto=B(t.label)+(ms?' is reached':' starts')+' once '+t.deps.map(d=>B(d.label)).join(' and ')+(t.deps.length>1?' are':' is')+' finished'+(t.s!=null?' ('+fd(t.s)+')':'')+'.';
else auto=B(t.label)+' '+(when||(ms?'is a milestone':'begins'))+'.';
if(!ms&&t.s!=null&&t.e!=null)auto+=' It takes '+fdur(t.e-t.s)+' and ends on '+fd(t.e)+'.';
else if(!ms&&t.d!=null)auto+=' It takes '+fdur(t.d)+'.';
const st=t.tags.includes('done')?'Done':t.tags.includes('active')?'In progress':t.tags.includes('crit')?'Critical':'';
const tag=[t.section!=null?K.groups[t.section].title:'',st].filter(Boolean).join(' · ');
const chip=t.s!=null?fd(t.s):'';
if(lis.length){const last=t.deps.reduce((a,d,k)=>(d.e??-1)>(t.deps[a].e??-1)?k:a,0);const s=K.edgeStep(lis[last],{auto,tag,title:t.label});s.chip=chip;s.nodes=[...t.deps.map(d=>d.n.id),t.n.id];steps.push(s)}
else steps.push(K.nodeStep(t.n,{auto,tag}));
if(t.s!=null)t.n.note=(ms?'Date: ':'When: ')+fd(t.s)+(!ms&&t.e!=null?' → '+fd(t.e):'')+(st?' · '+st:'');
});
return {type:'gantt',nodes:[...K.nodes.values()],links:K.links,steps,groups:K.groups,diagramTitle:title};
}
/* ---------- mermaid: pie ---------- */
/** @param {string} first @param {string[]} ls @returns {Graph} */
export function parsePie(first,ls){
let title=(first.match(/^pie\b(?:\s+showData)?(?:\s+title\s+(.+))?$/i)||[])[1]||'';const slices=/** @type {Array<{label:string,v:number}>} */([]);
for(const line of ls){let m;
if(m=line.match(/^title\s+(.+)$/i)){title=m[1];continue}
if(m=line.match(/^"([^"]+)"\s*:\s*(-?\d+(?:\.\d+)?)$/))slices.push({label:cleanText(m[1]),v:+m[2]});
}
if(!slices.length)throw new Error('No slices found in the pie chart. Write them like "Dogs" : 42');
const tot=slices.reduce((s,x)=>s+Math.max(0,x.v),0)||1,max=Math.max(...slices.map(x=>x.v),1e-9);
const pct=(/** @type {number} */v)=>{const p=v/tot*100;return (p>=10||Number.isInteger(p)?Math.round(p):Math.round(p*10)/10)+'%'};
const fmt=(/** @type {number} */v)=>Number.isInteger(v)?v.toLocaleString('en-US'):String(v);
const nodes=slices.map((s,i)=>({id:'slice'+(i+1),label:s.label+' · '+pct(s.v),shape:'box',group:null,ci:i,hk:.35+2.3*Math.max(0,s.v)/max,gx:i*2.7,gy:0,note:fmt(s.v)+' of '+fmt(tot)+' in total ('+pct(s.v)+').'}));
const rank=slices.map((s,i)=>i).sort((a,b)=>slices[b].v-slices[a].v);
const steps=rank.map((i,k)=>{const s=slices[i];
const pos=k===0?'the biggest share':k===rank.length-1&&rank.length>2?'the smallest share':'number '+(k+1)+' of '+rank.length;
return {kind:'node',nodes:[nodes[i].id],title:s.label,chip:pct(s.v),auto:'**'+s.label+'** is **'+pct(s.v)+'** of the total ('+fmt(s.v)+' of '+fmt(tot)+') — '+pos+'.'}});
return {type:'pie',nodes,links:[],steps,groups:[],fixed:true,diagramTitle:cleanText(title)};
}
/* ---------- mermaid: mindmap ---------- */
/** @param {string} code @returns {Graph} */
export function parseMindmap(code){
let raw=code.replace(/\r/g,'').split('\n');
if(raw.find(l=>l.trim())?.trim()==='---'){const a=raw.findIndex(l=>l.trim()==='---'),b=raw.findIndex((l,i)=>i>a&&l.trim()==='---');if(b>a)raw=raw.slice(b+1)}
raw=raw.map(l=>l.replace(/%%.*$/,'').replace(/\t/g,' ')).filter(l=>l.trim());
const hi=raw.findIndex(l=>/^\s*mindmap\b/.test(l));raw=raw.slice(hi+1);
const K=graphKit(),steps=/** @type {Step[]} */([]),stack=/** @type {Array<{ind:number,n:FxNode}>} */([]);let count=0;
/** @type {Array<[RegExp,string]>} */
const FORMS=[[/^\(\((.*)\)\)$/s,'circle'],[/^\)\)(.*)\(\($/s,'pill'],[/^\)(.*)\($/s,'pill'],[/^\{\{(.*)\}\}$/s,'box'],[/^\((.*)\)$/s,'pill'],[/^\[(.*)\]$/s,'box']];
for(const l of raw){
const t=l.trim();if(/^::icon\(/.test(t)||/^:::/.test(t))continue;
const ind=/** @type {RegExpMatchArray} */(l.match(/^ */))[0].length;
const body=t.replace(/:::[\w\s-]+$/,'').trim();let label=body,shape='box';
const idm=body.match(/^([\w-]+)(?=[[({)])/);const rest=idm?body.slice(idm[0].length):body;
for(const [re,sh] of FORMS){const m=rest.match(re);if(m){label=m[1];shape=sh;break}}
if(label===body&&idm)label=body;
const n=K.node('m'+(++count),cleanText(label)||'…',shape);
while(stack.length&&stack[stack.length-1].ind>=ind)stack.pop();
const parent=stack.length?stack[stack.length-1].n:null;
if(parent){
n.group=parent.group!=null?parent.group:(stack.length===1?(K.groups.push({title:n.label}),K.groups.length-1):null);
const li=K.link(parent,n,{});const top=stack.length===1;
steps.push(K.edgeStep(li,{title:n.label,auto:top?'One main part of **'+parent.label+'** is **'+n.label+'**.':'**'+parent.label+'** includes **'+n.label+'**.',tag:n.group!=null?K.groups[n.group].title:''}));
}else n.group=null;
stack.push({ind,n});
}
const N=[...K.nodes.values()];if(!N.length)throw new Error('The mindmap is empty.');
const roots=N.filter(n=>!K.links.some(l=>l.to===n.id));roots.forEach(r=>r.icon='💡');
return {type:'mindmap',nodes:N,links:K.links,steps,groups:K.groups,noZones:true};
}
/* ---------- mermaid: fixed-position helpers ---------- */
/** Straight / elbow arrow points for parsers that place their own nodes (every node has gx/gy). @param {FxNode[]} nodes @param {FxLink[]} links */
export function routeFixed(nodes,links){
const by=/** @type {Map<string,PlacedNode>} */(new Map(nodes.map(n=>[n.id,n])));
links.forEach(l=>{
const a=by.get(l.from),b=by.get(l.to);if(!a||!b||a===b){l.pts=null;return}
if(Math.abs(a.gx-b.gx)<.02){const s=Math.sign(b.gy-a.gy)||1;l.pts=[[a.gx,a.gy+s*T0],[b.gx,b.gy-s*T1]];return}
const s=Math.sign(b.gx-a.gx)||1;
if(Math.abs(a.gy-b.gy)<.02){l.pts=[[a.gx+s*T0,a.gy],[b.gx-s*T1,b.gy]];return}
const x0=a.gx+s*T0,x1=b.gx-s*T1,xm=s>0?Math.min((x0+x1)/2,x1-.8):Math.max((x0+x1)/2,x1+.8);
l.pts=[[a.gx+s*T0,a.gy],[xm,a.gy],[xm,b.gy],[b.gx-s*T1,b.gy]];
});
}
/** @param {string} s @param {string} k */
export const kv=(s,k)=>{const m=s.match(new RegExp('\\b'+k+'\\s*:\\s*(?:"([^"]*)"|([^\\s,]+))'));return m?(m[1]??m[2]):null};
/* ---------- mermaid: journey ---------- */
/** @param {string[]} ls @returns {Graph} */
export function parseJourney(ls){
const K=graphKit(),tasks=/** @type {Array<{n:FxNode,sc:number,raw:string,who:string[],section:number|null}>} */([]);let title='',section=/** @type {number|null} */(null);
// index 0 is never used: scores are clamped to 1..5
const MOOD=/** @type {Array<[string,string]>} */([null,['very unhappy','😫'],['frustrating','😟'],['okay','😐'],['good','🙂'],['great','😀']]);
for(const line of ls){let m;
if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue}
if(/^(accTitle|accDescr)\b/.test(line))continue;
if(m=line.match(/^section\s+(.+)$/)){K.groups.push({title:cleanText(m[1])});section=K.groups.length-1;continue}
if(m=line.match(/^(.+?)\s*:\s*(\d+(?:\.\d+)?)\s*(?::\s*(.*))?$/)){
const sc=Math.max(1,Math.min(5,Math.round(+m[2]))),who=(m[3]||'').split(',').map(s=>cleanText(s)).filter(Boolean);
const n=K.node('t'+(tasks.length+1),cleanText(m[1]));n.group=section;n.hk=.45+.32*sc;n.icon=MOOD[sc][1];
n.note='Feeling: '+MOOD[sc][0]+' ('+sc+' out of 5).'+(who.length?' Who: '+who.join(', ')+'.':'');
tasks.push({n,sc,raw:String(sc),who,section});
}
}
if(!tasks.length)throw new Error('No steps found in the journey. Write them like Pay for ticket: 3: Customer');
const B=(/** @type {string} */s)=>'**'+s+'**',steps=/** @type {Step[]} */([]);
tasks.forEach((t,i)=>{
const feel=MOOD[t.sc][0]
,whoTxt=t.who.length?' for '+t.who.map(B).join(t.who.length>2?', ':' and ').replace(/, ([^,]*)$/,' and $1'):'';
const auto=(i===0?'It starts with '+B(t.n.label)+'. ':'Next: '+B(t.n.label)+'. ')+'This feels '+B(feel)+whoTxt+' ('+t.raw+' out of 5).'+(t.sc<=2?' A pain point worth fixing.':'');
const tag=t.section!=null?K.groups[t.section].title:'',chip=MOOD[t.sc][1]+' '+t.raw+'/5';
if(i===0){const s=K.nodeStep(t.n,{auto,tag});s.chip=chip;steps.push(s)}
else steps.push(K.edgeStep(K.link(tasks[i-1].n,t.n,{arrow:true}),{auto,tag,chip,title:t.n.label}));
});
return {type:'journey',nodes:[...K.nodes.values()],links:K.links,steps,groups:K.groups,diagramTitle:title};
}
/* ---------- mermaid: timeline ---------- */
/** @param {string[]} ls @returns {Graph} */
export function parseTimeline(ls){
const K=graphKit(),periods=/** @type {Array<{label:string,ev:string[],section:number|null}>} */([]);let title='',section=/** @type {number|null} */(null);
for(const line of ls){let m;
if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue}
if(/^(accTitle|accDescr|direction)\b/.test(line))continue;
if(m=line.match(/^section\s+(.+)$/)){K.groups.push({title:cleanText(m[1])});section=K.groups.length-1;continue}
if(line.startsWith(':')){const p=periods[periods.length-1];if(p)line.split(':').map(cleanText).filter(Boolean).forEach(e=>p.ev.push(e));continue}
const parts=line.split(/\s*:\s+|\s+:\s*/);
periods.push({label:cleanText(parts[0]),ev:parts.slice(1).map(cleanText).filter(Boolean),section});
}
if(!periods.length)throw new Error('No periods found in the timeline. Write them like 2024 : Shop opens');
const steps=/** @type {Step[]} */([]),B=(/** @type {string} */s)=>'**'+s+'**';let prev=/** @type {FxNode|null} */(null);
periods.forEach((p,i)=>{
const n=K.node('p'+(i+1),p.label,'box');n.group=p.section;n.gx=i*DX;n.gy=0;n.icon='📅';
const evs=p.ev.map((e,k)=>{const en=K.node('p'+(i+1)+'e'+(k+1),e,'pill');en.group=p.section;en.gx=i*DX;en.gy=(k+1)*2.9;K.link(n,en,{dotted:true});return en});
const tag=p.section!=null?K.groups[p.section].title:'';
const auto=B(p.label)+(evs.length?': '+p.ev.map(B).join(evs.length>2?', ':' and ').replace(/, ([^,]*)$/,' and $1')+'.':'.');
let s;
if(prev)s=K.edgeStep(K.link(prev,n,{arrow:true}),{auto,tag,title:p.label});else s=K.nodeStep(n,{auto,tag});
s.nodes=[...(prev?[prev.id]:[]),n.id,...evs.map(e=>e.id)];
if(p.ev.length)n.note=p.ev.join(' · ');
steps.push(s);prev=n;
});
const N=[...K.nodes.values()];routeFixed(N,K.links);
return {type:'timeline',nodes:N,links:K.links,steps,groups:K.groups,fixed:true,diagramTitle:title};
}
/* ---------- mermaid: quadrant ---------- */
/** @param {string[]} ls @returns {Graph} */
export function parseQuadrant(ls){
let title='',xa=['',''],ya=['',''];const q=['','','',''],pts=/** @type {Array<{label:string,x:number,y:number}>} */([]);
for(const line of ls){let m;
if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue}
if(m=line.match(/^([xy])-axis\s+(.+?)(?:\s*-->\s*(.+))?$/)){const v=[cleanText(m[2]),cleanText(m[3]||'')];if(m[1]==='x')xa=v;else ya=v;continue}
if(m=line.match(/^quadrant-([1-4])\s+(.+)$/)){q[+m[1]-1]=cleanText(m[2]);continue}
if(/^(classDef|accTitle|accDescr)\b/.test(line))continue;
if(m=line.match(/^(.+?)(?::::[\w-]+)?\s*:\s*\[\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*\]/))pts.push({label:cleanText(m[1]),x:Math.max(0,Math.min(1,+m[2])),y:Math.max(0,Math.min(1,+m[3]))});
}
if(!pts.length)throw new Error('No points found in the quadrant chart. Write them like Gift cards: [0.3, 0.8]');
const qn=(/** @type {{x:number,y:number}} */p)=>p.y>=.5?(p.x>=.5?0:1):(p.x<.5?2:3);
const groups=q.map((t,i)=>({title:t||['Top right','Top left','Bottom left','Bottom right'][i]}));
const S=Math.max(12,Math.sqrt(pts.length)*4.4);
const nodes=pts.map((p,i)=>({id:'pt'+(i+1),label:p.label,shape:'box',group:qn(p),gx:p.x*S,gy:(1-p.y)*S,note:''}));
for(let it=0;it<60;it++)for(let i=0;i<nodes.length;i++)for(let j=i+1;j<nodes.length;j++){
const a=nodes[i],b=nodes[j],dx=b.gx-a.gx,dy=b.gy-a.gy,d=Math.hypot(dx,dy),min=3;
if(d<min){const k=(min-d)/2/(d||1),ux=d?dx:1,uy=d?dy:0;a.gx-=ux*k;a.gy-=uy*k;b.gx+=ux*k;b.gy+=uy*k}
}
/** @param {number} v @param {string[]} ax @param {string} dir */
const lvl=(v,ax,dir)=>
(v>=.5?ax[1]:ax[0])||((v>=.5?'high':'low')+' '+dir+' ('+Math.round(v*100)+'%)');
const B=(/** @type {string} */s)=>'**'+s+'**';
const steps=pts.map((p,i)=>{const n=nodes[i],g=groups[n.group].title;
n.note='Across: '+Math.round(p.x*100)+'%'+(xa[0]?' ('+xa[0]+' → '+(xa[1]||'')+')':'')+'. Up: '+Math.round(p.y*100)+'%'+(ya[0]?' ('+ya[0]+' → '+(ya[1]||'')+')':'')+'.';
const auto=B(p.label)+' is '+B(lvl(p.x,xa,'across').toLowerCase())+' and '+B(lvl(p.y,ya,'up').toLowerCase())+', so it lands in '+B(g)+'.';
return {kind:'node',nodes:[n.id],title:p.label,chip:g,auto,tag:g}});
const order=steps.map((s,i)=>i).sort((a,b)=>nodes[a].group-nodes[b].group||pts[b].y-pts[a].y);
return {type:'quadrant',nodes,links:[],steps:order.map(i=>steps[i]),groups,fixed:true,diagramTitle:title||(xa[0]&&ya[0]?xa[0].replace(/^low\s+/i,'')+' vs '+ya[0].replace(/^low\s+/i,''):'')};
}
/* ---------- mermaid: git graph ---------- */
/** @typedef {{name:string,lane:number,g:number,head:GitCommit|null,count:number}} GitBranch */
/** @typedef {{id?:string|null,tag?:string|null,type?:string,kind:string,from?:string}} GitOpts */
/** @typedef {{n:FxNode,b:GitBranch,parent:GitCommit|null,o:GitOpts}} GitCommit */
/** @param {string[]} ls @returns {Graph} */
export function parseGit(ls){
const K=graphKit(),branches=/** @type {Map<string,GitBranch>} */(new Map()),commits=/** @type {GitCommit[]} */([]),steps=/** @type {Step[]} */([]),byId=/** @type {Map<string|null,GitCommit>} */(new Map()),B=(/** @type {string} */s)=>'**'+s+'**';
let cur='main';
/** @param {string} name @returns {GitBranch} */
const br=name=>{name=name.replace(/^"|"$/g,'');if(!branches.has(name)){K.groups.push({title:name});branches.set(name,{name,lane:branches.size,g:K.groups.length-1,head:null,count:0})}return /** @type {GitBranch} */(branches.get(name))};
br('main');
/** @param {GitOpts} o @returns {GitCommit} */
const add=(o)=>{
const b=br(cur),i=commits.length;b.count++;
const id=o.id||(o.kind==='merge'?'Merge '+o.from:b.name+' #'+b.count);
const n=K.node('c'+(i+1),cleanText(id),o.kind==='merge'?'hex':'circle');n.group=b.g;n.gx=i*DX;n.gy=b.lane*DY;
if(o.tag){n.icon='🏷️';n.note='Tag: '+o.tag+'.'}
if(o.type==='HIGHLIGHT')n.icon=n.icon||'⭐';if(o.type==='REVERSE')n.icon='↩️';if(o.kind==='pick')n.icon='🍒';
const c={n,b,parent:b.head,o};commits.push(c);if(o.id)byId.set(o.id,c);b.head=c;return c;
};
for(const line of ls){let m;
if(/^(accTitle|accDescr|%%)/.test(line))continue;
if(m=line.match(/^commit\b(.*)$/)){
const r=m[1],c=add({id:kv(r,'id')||kv(r,'msg'),tag:kv(r,'tag'),type:(kv(r,'type')||'').toUpperCase(),kind:'commit'});
const p=c.parent,tagTxt=c.o.tag?' It is marked as '+B(c.o.tag)+'.':'';
let auto;
if(!p)auto='The project starts on '+B(c.b.name)+' with '+B(c.n.label)+'.';
else if(p.b!==c.b)auto='A separate copy called '+B(c.b.name)+' splits off from '+B(p.b.name)+' at '+B(p.n.label)+', and saves its first change: '+B(c.n.label)+'.';
else auto=B(c.b.name)+' saves a new change: '+B(c.n.label)+'.';
if(c.o.type==='REVERSE')auto+=' This change undoes an earlier one.';
auto+=tagTxt;
if(p)steps.push(K.edgeStep(K.link(p.n,c.n,{arrow:true}),{auto,tag:c.b.name,chip:c.o.tag||'',title:c.n.label}));
else steps.push(K.nodeStep(c.n,{auto,tag:c.b.name}));
continue;
}
if(m=line.match(/^branch\s+("[^"]+"|\S+)/)){const nb=br(m[1]);nb.head=br(cur).head;cur=nb.name;continue}
if(m=line.match(/^(?:checkout|switch)\s+("[^"]+"|\S+)/)){cur=br(m[1]).name;continue}
if(m=line.match(/^merge\s+("[^"]+"|\S+)(.*)$/)){
const from=br(m[1]),r=m[2],into=br(cur),p=into.head,oh=from.head;
const c=add({id:kv(r,'id'),tag:kv(r,'tag'),type:(kv(r,'type')||'').toUpperCase(),kind:'merge',from:from.name});
const ids=[];if(p)ids.push(p.n.id);let li=null;
if(p)K.link(p.n,c.n,{arrow:true});
if(oh){li=K.link(oh.n,c.n,{arrow:true});ids.push(oh.n.id)}
const auto='All the work on '+B(from.name)+' is merged back into '+B(into.name)+'.'+(c.o.tag?' This version is marked as '+B(c.o.tag)+'.':'');
const s=li!=null?K.edgeStep(li,{auto,tag:into.name,chip:c.o.tag||'merge',title:from.name+' → '+into.name}):K.nodeStep(c.n,{auto,tag:into.name});
s.nodes=[...ids,c.n.id];steps.push(s);continue;
}
if(m=line.match(/^cherry-pick\b(.*)$/)){
const src=byId.get(kv(m[1],'id')),c=add({id:src?src.n.label+' (copy)':null,tag:kv(m[1],'tag'),kind:'pick'}),p=c.parent;
if(p)K.link(p.n,c.n,{arrow:true});
const auto=src?'One change, '+B(src.n.label)+', is copied from '+B(src.b.name)+' onto '+B(c.b.name)+' on its own.':B(c.b.name)+' copies in a single change from another branch.';
if(src){const s=K.edgeStep(K.link(src.n,c.n,{arrow:true,dotted:true}),{auto,tag:c.b.name,chip:'copy'});s.nodes=[...(p?[p.n.id]:[]),src.n.id,c.n.id];steps.push(s)}
else steps.push(K.nodeStep(c.n,{auto,tag:c.b.name}));
}
}
if(!commits.length)throw new Error('No commits found in the git graph.');
const N=[...K.nodes.values()];routeFixed(N,K.links);
return {type:'git',nodes:N,links:K.links,steps,groups:K.groups,fixed:true};
}
/* ---------- mermaid: helpers for the chart-like types ---------- */
/** @param {unknown} v @returns {v is number} */
export const isNum=v=>typeof v==='number';
/** @param {number} v */
export const fmtNum=v=>Number.isInteger(v)?v.toLocaleString('en-US'):v.toLocaleString('en-US',{maximumFractionDigits:2});
/** @param {string} s */
export const humanId=s=>{s=cleanText(s);return /\s/.test(s)||!/[_-]/.test(s)?s:s.replace(/[_-]+/g,' ').replace(/^./,c=>c.toUpperCase())};
/** @param {string[]} a @param {(s:string)=>string} B */
export const andList=(a,B)=>{a=a.map(B);return a.length<2?a.join(''):a.slice(0,-1).join(', ')+' and '+a[a.length-1]};
/** @param {string} s */
export const lcFirst=s=>/^[A-Z][a-z]/.test(s)?s[0].toLowerCase()+s.slice(1):s;
/** @param {string} s @returns {string[]} */
export function splitArgs(s){const out=[];let cur='',q=false;for(const ch of s){if(ch==='"'){q=!q;continue}if(ch===','&&!q){out.push(cur.trim());cur='';continue}cur+=ch}if(cur.trim()||out.length)out.push(cur.trim());return out}
/** @param {string} l @returns {string[]} */
export function splitCsv(l){const out=[];let cur='',q=false;for(let i=0;i<l.length;i++){const ch=l[i];if(q){if(ch==='"'&&l[i+1]==='"'){cur+='"';i++}else if(ch==='"')q=false;else cur+=ch}else if(ch==='"')q=true;else if(ch===','){out.push(cur);cur=''}else cur+=ch}out.push(cur);return out.map(s=>s.trim())}
/* ---------- mermaid: xy chart ---------- */
/** @param {string[]} ls @returns {Graph} */
export function parseXY(ls){
/** @type {string[]|null} */ let cats=null;/** @type {number[]|null} */ let range=null;/** @type {number|null} */ let ymin=null;/** @type {number|null} */ let ymax=null;
let title='',yTitle='',xTitle='';
/** @type {{kind:string,name:string,v:number[]}[]} */
const series=[];
/** @param {string} s */
const list=s=>splitArgs(s).map(cleanText).filter(x=>x!=='');
for(const line of ls){let m;
if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue}
if(m=line.match(/^x-axis\s*(?:("[^"]*"|[^\s[]+)\s*)?(?:\[(.*)\]|(-?[\d.]+)\s*-->\s*(-?[\d.]+))?\s*$/)){xTitle=cleanText(m[1]||'');if(m[2]!=null)cats=list(m[2]);else if(m[3]!=null)range=[+m[3],+m[4]];continue}
if(m=line.match(/^y-axis\s*(?:("[^"]*"|[^\s\d-][^\s]*)\s*)?(?:(-?[\d.]+)\s*-->\s*(-?[\d.]+))?\s*$/)){yTitle=cleanText(m[1]||'');if(m[2]!=null){ymin=+m[2];ymax=+m[3]}continue}
if(m=line.match(/^(bar|line)\s*(?:("[^"]*"|[^\s[]+)\s*)?\[(.*)\]\s*$/))series.push({kind:m[1],name:cleanText(m[2]||''),v:list(m[3]).map(Number).filter(x=>!isNaN(x))});
}
if(!series.length||!series.some(s=>s.v.length))throw new Error('No data found in the xy chart. Write it like bar [5000, 6000, 7500]');
const n=Math.max(...series.map(s=>s.v.length));
if(!cats||cats.length<n){const c=cats||[];cats=Array.from({length:n},(_,i)=>c[i]??(range?fmtNum(Math.round((range[0]+(range[1]-range[0])*(n>1?i/(n-1):0))*100)/100):String(i+1)))}
const all=series.flatMap(s=>s.v),lo=ymin!=null?ymin:Math.min(0,...all),hi=Math.max(ymax!=null?ymax:-Infinity,...all),span=hi-lo||1;
/** @type {Record<string,number>} */ const counts={bar:0,line:0};
series.forEach(s=>{counts[s.kind]++;s.name=s.name||(series.length===1?(yTitle||'Value'):(s.kind==='bar'?'Bars':'Line')+(series.filter(x=>x.kind===s.kind).length>1?' '+counts[s.kind]:''))});
const multi=series.length>1,groups=multi?series.map(s=>({title:s.name})):[],nodes=/** @type {FxNode[]} */([]),links=/** @type {FxLink[]} */([]);
series.forEach((s,si)=>s.v.forEach((v,i)=>{
/** @type {FxNode} */ const nd={id:'s'+si+'p'+i,label:cats[i]+' · '+fmtNum(v),shape:s.kind==='line'?'circle':'box',group:multi?si:null,ci:si,gx:i*2.7,gy:si*2.9,hk:.3+2.3*Math.max(0,v-lo)/span,
note:(multi?s.name+': ':'')+fmtNum(v)+(yTitle&&!multi?' ('+yTitle+')':'')+'.'};
if(s.kind==='line')nd.icon='📈';nodes.push(nd);
if(s.kind==='line'&&i>0)links.push({from:'s'+si+'p'+(i-1),to:nd.id,label:'',dotted:false,arrow:true});
}));
routeFixed(nodes,links);
const B=(/** @type {string} */s)=>'**'+s+'**',main=series[0];
const steps=cats.slice(0,n).map((c,i)=>{
const ids=series.filter(s=>i<s.v.length).map(s=>'s'+series.indexOf(s)+'p'+i);
let auto;
if(!multi){const v=main.v[i],p=i?main.v[i-1]:null,mx=Math.max(...main.v),mn=Math.min(...main.v);
auto=(i===0?'It starts at '+B(fmtNum(v))+' in '+B(c):'In '+B(c)+': '+B(fmtNum(v)))+(p!=null&&p?(v===p?', the same as '+cats[i-1]:(v>p?', up ':', down ')+Math.abs(Math.round((v-p)/Math.abs(p)*100))+'% from '+cats[i-1]):'')+'.'+(v===mx&&main.v.length>2?' This is the highest point.':v===mn&&main.v.length>2?' This is the lowest point.':'');}
else auto=B(c)+': '+series.filter(s=>i<s.v.length).map(s=>s.name+' '+B(fmtNum(s.v[i]))).join(', ')+'.';
const li=links.findIndex(l=>l.to===ids.find(id=>nodes.find(x=>x.id===id)?.shape==='circle'));
/** @type {Step} */ const s=li>=0?{kind:'edge',link:li,reverse:false,from:links[li].from,to:links[li].to,nodes:ids,title:c,chip:multi?'':fmtNum(main.v[i]),auto}:{kind:'node',nodes:ids,title:c,chip:multi?'':fmtNum(main.v[i]),auto};
if(li>=0&&!ids.includes(links[li].from))s.nodes=[links[li].from,...ids];
return s;
});
return {type:'xy',nodes,links,steps,groups,fixed:true,diagramTitle:title||(yTitle&&xTitle?yTitle+' by '+lcFirst(xTitle):yTitle)};
}
/* ---------- mermaid: sankey ---------- */
/** @param {string[]} ls @returns {Graph} */
export function parseSankey(ls){
const K=graphKit();
/** @type {{a:string,b:string,v:number,li:number}[]} */
const flows=[];
for(const line of ls){const f=splitCsv(line);if(f.length<3)continue;const v=+f[2];if(!f[0]||!f[1]||isNaN(v))continue;flows.push({a:cleanText(f[0]),b:cleanText(f[1]),v,li:-1})}
if(!flows.length)throw new Error('No flows found in the sankey diagram. Write each line as From,To,Amount');
/** @param {string} s */
const id=s=>'k_'+s;
/** @type {Map<string,number>} */ const inn=new Map();
/** @type {Map<string,number>} */ const out=new Map();
/** @param {Map<string,number>} m @param {string} k @param {number} v */
const add=(m,k,v)=>m.set(k,(m.get(k)||0)+v);
flows.forEach(f=>{f.li=K.link(K.node(id(f.a),f.a),K.node(id(f.b),f.b),{label:fmtNum(f.v),arrow:true});add(out,f.a,f.v);add(inn,f.b,f.v)});
const N=[...K.nodes.values()],thr=(/** @type {string} */s)=>Math.max(inn.get(s)||0,out.get(s)||0),mx=Math.max(...N.map(n=>thr(n.label)))||1;
N.forEach(n=>{const i=inn.get(n.label)||0,o=out.get(n.label)||0;n.hk=.45+1.6*thr(n.label)/mx;
n.note=[i?'Comes in: '+fmtNum(i)+'.':'',o?'Goes out: '+fmtNum(o)+'.':'',i&&o&&Math.abs(i-o)>1e-9?(i>o?'Keeps ':'Adds ')+fmtNum(Math.abs(i-o))+'.':''].filter(Boolean).join(' ');
if(!i)n.icon='🚰';else if(!o)n.icon='🎯'});
const B=(/** @type {string} */s)=>'**'+s+'**';
const steps=flows.map(f=>{const share=Math.round(f.v/(out.get(f.a)||1)*100);
return K.edgeStep(f.li,{chip:fmtNum(f.v),auto:B(f.a)+' sends '+B(fmtNum(f.v))+' to '+B(f.b)+(share<100?' — '+share+'% of everything leaving '+f.a+'.':' — all of it.')})});
return {type:'sankey',nodes:N,links:K.links,steps,groups:[]};
}
/* ---------- mermaid: block ---------- */
/** @typedef {{span:number,cols?:number,items?:BlockItem[],g?:number|null,space?:boolean,n?:FxNode,w?:number,h?:number,x?:number,y?:number,ww?:number,ncol?:number,cw?:number,rows?:BlockItem[][]}} BlockItem */
/** @typedef {{a:string,b:string,label:string,arrow:boolean,dotted:boolean,aName?:string,bName?:string}} BlockLink */
/** @param {string[]} ls @returns {Graph} */
export function parseBlock(ls){
/** @type {Map<string,FxNode>} */ const nodes=new Map();
/** @type {BlockLink[]} */ const links=[];
/** @type {Group[]} */ const groups=[];
/** @type {BlockItem} */ const root={cols:0,items:[],g:null,span:1};
const stack=[root];
/** @type {Map<string,BlockItem>} */ const byBlock=new Map();
const OPEN=[['(((',')))','circle'],['((','))','circle'],['([','])','pill'],['[(',')]','cyl'],['[[',']]','box'],['{{','}}','hex'],['<[',']>','pill'],['[/','/]','box'],['[\\','\\]','box'],['[/','\\]','box'],['[\\','/]','box'],['[',']','box'],['(',')','pill'],['{','}','hex'],['>',']','box']];
/** @param {string} line */
const tokens=line=>{const out=[];let i=0;
while(i<line.length){
while(line[i]===' ')i++;if(i>=line.length)break;
const idm=line.slice(i).match(/^[^\s[\](){}<>:"]+/);if(!idm){i++;continue}
const id=idm[0];let label=null,shape='box',arrow=false;i+=id.length;
for(const [o,c,sh] of OPEN){if(!line.startsWith(o,i))continue;let j=i+o.length,q=false;
for(;j<line.length;j++){if(line[j]==='"')q=!q;else if(!q&&line.startsWith(c,j))break}
label=cleanText(line.slice(i+o.length,j));shape=sh;arrow=o==='<[';i=j+c.length;break}
if(arrow){const dm=line.slice(i).match(/^\(([\w,\s]+)\)/);if(dm)i+=dm[0].length;label=(label||'').replace(/ /g,' ').trim()||(/** @type {Record<string,string>} */({right:'→',left:'←',up:'↑',down:'↓'})[(dm?dm[1]:'').split(',')[0].trim()]||'→')}
let span=1;const sm=line.slice(i).match(/^:(\d+)/);if(sm){span=+sm[1];i+=sm[0].length}
out.push({id,label,shape,span,arrow});
}return out};
for(const line of ls){let m;
if(/^(classDef|class|style|accTitle|accDescr)\b/.test(line))continue;
const top=stack[stack.length-1];
if(m=line.match(/^columns\s+(\d+|auto)$/)){top.cols=m[1]==='auto'?0:+m[1];continue}
if(m=line.match(/^block(?::([^\s:[]+))?(?:\["?([^"\]]*)"?\])?(?::(\d+))?$/)){
groups.push({title:cleanText(m[2]||'')||humanId(m[1]||'Group '+(groups.length+1))});
/** @type {BlockItem} */ const c={cols:0,items:[],g:groups.length-1,span:+(m[3]||1)};if(m[1])byBlock.set(m[1],c);(top.items||[]).push(c);stack.push(c);continue}
if(line==='end'){if(stack.length>1)stack.pop();continue}
if(m=line.match(/^([^\s"]+)\s*(?:--\s*"([^"]*)"\s*(-->|---)|(-->|---|==>|-\.->|-\.-))\s*([^\s"]+)$/)){links.push({a:m[1],b:m[5],label:cleanText(m[2]||''),arrow:/>$/.test(m[3]||m[4]),dotted:/\./.test(m[4]||'')});continue}
for(const t of tokens(line)){
const items=top.items||[];
if(t.id==='space'){items.push({space:true,span:t.span});continue}
if(!nodes.has(t.id))nodes.set(t.id,{id:t.id,label:t.label||t.id,shape:t.shape,group:top.g??null});
const n=/** @type {FxNode} */(nodes.get(t.id));if(t.label){n.label=t.label;n.shape=t.shape}if(t.arrow)n.icon=/** @type {Record<string,string>} */({'↓':'⬇️','↑':'⬆️','←':'⬅️'})[n.label]||'➡️';
items.push({n,span:t.span});
}
}
/** @param {BlockItem} it @returns {FxNode[]} */
const leaves0=it=>it.items?it.items.flatMap(leaves0):it.n?[it.n]:[];
links.forEach(l=>{for(const e of /** @type {('a'|'b')[]} */(['a','b'])){const blk=byBlock.get(l[e]);if(!nodes.has(l[e])&&blk){const ls=leaves0(blk);if(ls.length){const nm=groups[/** @type {number} */(blk.g)].title;if(e==='a')l.aName=nm;else l.bName=nm;l[e]=ls[Math.floor((ls.length-1)/2)].id}}}});
links.forEach(l=>{for(const k of [l.a,l.b])if(!nodes.has(k)){/** @type {FxNode} */ const nn={id:k,label:k,shape:'box',group:null};nodes.set(k,nn);(root.items||[]).push({n:nn,span:1})}});
if(!nodes.size)throw new Error('No blocks found in the block diagram.');
/** @param {BlockItem} c @returns {{w:number,h:number}} */
const size=c=>{const items=c.items||[];items.forEach(it=>{if(it.items)Object.assign(it,size(it));else{it.w=it.span;it.h=1}});
const cols=c.cols||items.reduce((s,it)=>s+it.span,0)||1;c.ncol=cols;
const cw=Math.max(1,...items.map(it=>(it.w||0)/Math.min(it.span,cols)));c.cw=cw;
let col=0,y=0,rh=0;const rows=/** @type {BlockItem[][]} */([[]]);c.rows=rows;
items.forEach(it=>{const sp=Math.min(it.span,cols);if(col+sp>cols){y+=rh;rh=0;col=0;rows.push([])}it.x=col*cw;it.y=y;it.ww=sp*cw;col+=sp;rh=Math.max(rh,it.h||0);rows[rows.length-1].push(it)});
return {w:cols*cw,h:y+rh}};
size(root);
/** @param {BlockItem} c @param {number} ox @param {number} oy @returns {void} */
const place=(c,ox,oy)=>(c.items||[]).forEach(it=>{const x=it.x||0,y=it.y||0,ww=it.ww||0;if(it.items)place(it,ox+x+(ww-(it.w||0))/2,oy+y);else if(it.n){it.n.gx=(ox+x+ww/2)*DX;it.n.gy=(oy+y+.5)*DY*1.15}});
place(root,0,0);
const N=[...nodes.values()],L=links.map(l=>({from:l.a,to:l.b,label:l.label,dotted:l.dotted,arrow:l.arrow,an:l.aName,bn:l.bName}));routeFixed(N,L);
const B=(/** @type {string} */s)=>'**'+s+'**',by=(/** @type {string} */id)=>/** @type {FxNode} */(nodes.get(id));/** @type {Step[]} */ let steps;
if(L.length)steps=L.map((l,i)=>{const a={...by(l.from)},b={...by(l.to)};if(l.an)a.label=l.an;if(l.bn)b.label=l.bn;
return {kind:'edge',link:i,reverse:false,from:a.id,to:b.id,nodes:[a.id,b.id],title:a.label+' → '+b.label,chip:l.label,tag:a.group!=null?groups[a.group].title:'',
auto:l.label?B(a.label)+' → '+B(b.label)+': '+l.label+'.':l.arrow?B(a.label)+' hands over to '+B(b.label)+'.':B(a.label)+' is connected to '+B(b.label)+'.'}});
else{const st=/** @type {Step[]} */([]);steps=st;const leaves=leaves0,rows=root.rows||[],gt=(/** @type {BlockItem} */it)=>groups[/** @type {number} */(it.g)].title;
rows.forEach((row,ri)=>{const ns=row.flatMap(leaves);if(!ns.length)return;
const inner=row.filter(it=>it.items&&leaves(it).length).map(it=>B(gt(it))+' holds '+andList(leaves(it).map(n=>n.label),B));
st.push({kind:'node',nodes:ns.map(n=>n.id),title:rows.length>1?'Row '+(ri+1):'Blocks',auto:(rows.length>1?'Row '+(ri+1)+' has ':'This has ')+andList(/** @type {string[]} */(row.map(it=>it.items?gt(it):it.n?it.n.label:null).filter(Boolean)),B)+'.'+(inner.length?' '+inner.join('. ')+'.':'')})});}
return {type:'block',nodes:N,links:L,steps,groups,fixed:true};
}
/* ---------- mermaid: architecture ---------- */
/** @type {Record<string,string>} */
export const ARCH_ICON={cloud:'☁️',database:'🗄️',disk:'💾',internet:'🌐',server:'🖥️'};
/** @param {string[]} ls @returns {Graph} */
export function parseArch(ls){
const K=graphKit(),gid=new Map(),edges=[];
/** @param {FxNode} n @param {string|undefined} ic */
const icon=(n,ic)=>{if(!ic)return;if(ic==='database'||ic==='disk')n.shape='cyl';if(ic==='internet')n.shape='circle';
n.icon=ARCH_ICON[ic]||(/(db|sql|dynamo|rds|mongo|redis)/i.test(ic)?'🗄️':/(s3|storage|bucket|blob)/i.test(ic)?'💾':/(lambda|function)/i.test(ic)?'⚡':/(queue|sqs|kafka|pubsub)/i.test(ic)?'📨':'🧩')};
for(const line of ls){let m;
if(m=line.match(/^group\s+([\w-]+)\s*(?:\(([^)]*)\))?\s*(?:\[([^\]]*)\])?(?:\s+in\s+([\w-]+))?$/)){K.groups.push({title:cleanText(m[3]||'')||humanId(m[1]),icon:m[2]||''});gid.set(m[1],K.groups.length-1);continue}
if(m=line.match(/^(service|junction)\s+([\w-]+)\s*(?:\(([^)]*)\))?\s*(?:\[([^\]]*)\])?(?:\s+in\s+([\w-]+))?$/)){
const n=K.node(m[2],m[1]==='junction'?'Meeting point':cleanText(m[4]||'')||humanId(m[2]),m[1]==='junction'?'circle':'box');
n.group=m[5]&&gid.has(m[5])?gid.get(m[5]):null;if(m[1]==='junction'){n.icon='➕';n.junction=true}else icon(n,m[3]);continue}
if(m=line.match(/^([\w-]+)(?:\{group\})?\s*:\s*([LRTB])\s*(<)?-(?:\[([^\]]*)\]-|-)(>)?\s*([LRTB])\s*:\s*([\w-]+)(?:\{group\})?$/))edges.push({a:m[1],b:m[7],label:cleanText(m[4]||''),back:!!m[3],fwd:!!m[5]});
}
if(!K.nodes.size)throw new Error('No services found in the architecture diagram. Write them like service db(database)[Database]');
const B=(/** @type {string} */s)=>'**'+s+'**',steps=[];
for(const e of edges){
let a=K.nodes.get(e.a)||K.node(e.a,humanId(e.a)),b=K.nodes.get(e.b)||K.node(e.b,humanId(e.b));
if(e.back&&!e.fwd)[a,b]=[b,a];
const li=K.link(a,b,{label:e.label,arrow:e.back||e.fwd});
const auto=b.junction?B(a.label)+' joins the meeting point.':a.junction?'The meeting point continues to '+B(b.label)+'.':
(e.back&&e.fwd?B(a.label)+' and '+B(b.label)+' talk to each other':e.back||e.fwd?B(a.label)+' sends to '+B(b.label):B(a.label)+' is connected to '+B(b.label))+(e.label?': '+e.label:'')+'.';
steps.push(K.edgeStep(li,{auto,chip:e.label,tag:a.group!=null&&a.group===b.group?K.groups[a.group].title:''}));
}
const N=[...K.nodes.values()];
if(!steps.length)N.forEach(n=>steps.push(K.nodeStep(n,{auto:B(n.label)+(n.group!=null?' runs in '+B(K.groups[n.group].title):'')+'.',tag:n.group!=null?K.groups[n.group].title:''})));
return {type:'architecture',nodes:N,links:K.links,steps,groups:K.groups};
}
/* ---------- mermaid: C4 ---------- */
/** @param {string} first @param {string[]} ls @returns {Graph} */
export function parseC4(first,ls){
const K=graphKit(),rels=[];let title='',pending=null;
const level=(first.match(/^C4(\w+)/)||[])[1]||'Context';
for(const line of ls){let m;
if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue}
if(line==='{'){if(pending!=null){K.stack.push(pending);pending=null}continue}
if(line==='}'){K.stack.pop();continue}
if(!(m=line.match(/^(\w+)\s*\((.*)\)\s*(\{)?\s*(\})?$/)))continue;
const fn=m[1],a=splitArgs(m[2]).filter(x=>!/^\$/.test(x)).map(x=>x.replace(/^"|"$/g,'')),open=!!m[3]&&!m[4];pending=null;
if(/^(Update|Add|Show|Hide|Set)/.test(fn))continue;
if(/Boundary$/.test(fn)||(/^(Deployment_Node|Node)(_L|_R)?$/.test(fn)&&(open||m[3]))){
K.groups.push({title:cleanText(a[1]||a[0])+(a[2]&&!/Boundary$/.test(fn)?' ('+cleanText(a[2])+')':'')});
if(open)K.stack.push(K.groups.length-1);else if(!m[3])pending=K.groups.length-1;continue}
let e=fn.match(/^(Person|System|Container|Component|Node)(Db|Queue)?(_Ext)?(?:_[LR])?$/);
if(e){const [,base,sub,ext]=e,tech2=base==='Container'||base==='Component'||base==='Node';
const id=a[0],label=cleanText(a[1]||a[0]),tech=tech2?cleanText(a[2]||''):'',desc=cleanText(tech2?a[3]||'':a[2]||'');
const n=K.node(id,label);n.label=label;n.shape=sub==='Db'?'cyl':sub==='Queue'||base==='Person'?'pill':'box';
n.icon=base==='Person'?'🧑':sub==='Queue'?'📨':ext?'🌐':base==='Node'?'🖥️':'';if(!n.icon)delete n.icon;n.iconFallback=base==='Component'?'🧩':'📦';
n.note=[desc&&/[.!?]$/.test(desc)?desc:desc?desc+'.':'',tech?'Built with: '+tech+'.':'',ext?'Outside our own system.':''].filter(Boolean).join(' ');
continue}
if(e=fn.match(/^(Bi)?Rel(Index)?(?:_(?:U|Up|D|Down|L|Left|R|Right|Back|Neighbor))?$/)){
const r=e[2]?a.slice(1):a;if(r.length<2)continue;
let [from,to]=r;if(/_Back$/.test(fn))[from,to]=[to,from];
rels.push({from,to,label:cleanText(r[2]||''),tech:cleanText(r[3]||''),bi:!!e[1]});
}
}
if(!K.nodes.size)throw new Error('No people or systems found in the C4 diagram. Write them like Person(customer, "Customer")');
const B=(/** @type {string} */s)=>'**'+s+'**',steps=[];
for(const r of rels){
const a=K.nodes.get(r.from)||K.node(r.from,humanId(r.from)),b=K.nodes.get(r.to)||K.node(r.to,humanId(r.to));
const li=K.link(a,b,{label:r.label,arrow:true});
const verb=r.label?lcFirst(r.label):(r.bi?'works together with':'talks to');
const auto=B(a.label)+' '+verb+' '+B(b.label)+(r.tech?' (using '+r.tech+')':'')+'.'+(r.bi&&r.label?' This goes both ways.':'');
steps.push(K.edgeStep(li,{auto,chip:r.tech||'',tag:a.group!=null?K.groups[a.group].title:''}));
}
const N=[...K.nodes.values()];
if(!steps.length)N.forEach(n=>steps.push(K.nodeStep(n,{auto:B(n.label)+(n.note?': '+n.note:'.')})));
return {type:'c4',nodes:N,links:K.links,steps,groups:K.groups,diagramTitle:title||(/** @type {Record<string,string>} */({Context:'System context',Container:'Containers',Component:'Components',Dynamic:'How the parts talk',Deployment:'Where it runs'})[level]||'')};
}
/* ---------- mermaid: kanban ---------- */
/** @typedef {{text:string,meta:Record<string,string>}} KanbanItem */
/** @param {string} code @returns {Graph} */
export function parseKanban(code){
let raw=code.replace(/\r/g,'').split('\n');
if(raw.find(l=>l.trim())?.trim()==='---'){const a=raw.findIndex(l=>l.trim()==='---'),b=raw.findIndex((l,i)=>i>a&&l.trim()==='---');if(b>a)raw=raw.slice(b+1)}
raw=raw.map(l=>l.replace(/%%.*$/,'').replace(/\t/g,' ')).filter(l=>l.trim());
raw=raw.slice(raw.findIndex(l=>/^\s*kanban\b/.test(l))+1);
if(!raw.length)throw new Error('The kanban board is empty.');
const base=Math.min(...raw.map(l=>(l.match(/^ */)||[''])[0].length));
/** @type {(KanbanItem & {cards:KanbanItem[]})[]} */ const cols=[];
/** @param {string} t @returns {KanbanItem} */
const item=t=>{const meta=/** @type {Record<string,string>} */({});const mm=t.match(/@\{(.*)\}\s*$/);if(mm){t=t.slice(0,mm.index).trim();for(const x of mm[1].matchAll(/([\w-]+)\s*:\s*(?:'([^']*)'|"([^"]*)"|([^,}]+))/g))meta[x[1].toLowerCase()]=(x[2]??x[3]??x[4]).trim()}
const b=t.match(/^([^[\s]*)\[(.*)\]$/);return {text:cleanText(b?b[2]:t),meta}};
for(const l of raw){const ind=(l.match(/^ */)||[''])[0].length,t=l.trim();
if(ind<=base||!cols.length)cols.push({...item(t),cards:[]});else cols[cols.length-1].cards.push(item(t));}
const K=graphKit(),steps=/** @type {Step[]} */([]),B=(/** @type {string} */s)=>'**'+s+'**';
/** @type {Record<string,string>} */ const PRI={'very high':'🔴',high:'🟠',low:'🟢','very low':'⚪'};
/** @type {FxNode|null} */ let prev=null;
cols.forEach((c,i)=>{
K.groups.push({title:c.text});const g=K.groups.length-1;
const h=K.node('col'+(i+1),c.text,'box');h.group=g;h.gx=i*DX;h.gy=0;h.icon='📋';h.note=c.cards.length+' card'+(c.cards.length===1?'':'s')+'.';
const cs=c.cards.map((d,k)=>{const n=K.node('col'+(i+1)+'c'+(k+1),d.text.length>46?d.text.slice(0,44).replace(/\s+\S*$/,'')+'…':d.text,'pill');n.group=g;n.gx=i*DX;n.gy=(k+1)*2.9;
const pr=d.meta.priority;if(pr&&PRI[pr.toLowerCase()])n.icon=PRI[pr.toLowerCase()];
n.note=[d.text.length>46?d.text+'.':'',d.meta.assigned?'Assigned to '+d.meta.assigned+'.':'',pr?'Priority: '+pr+'.':'',d.meta.ticket?'Ticket: '+d.meta.ticket+'.':''].filter(Boolean).join(' ');
K.link(h,n,{dotted:true});return {n,d}});
const who=cs.filter(x=>x.d.meta.assigned).map(x=>x.d.meta.assigned),urgent=cs.filter(x=>/high/i.test(x.d.meta.priority||''));
const auto=(cs.length?B(c.text)+' has '+B(cs.length+' card'+(cs.length===1?'':'s'))+': '+andList(cs.map(x=>x.n.label),B)+'.':B(c.text)+' is empty right now.')
+(urgent.length?' '+andList(urgent.map(x=>x.n.label),B)+(urgent.length>1?' are':' is')+' high priority.':'')+(who.length?' Assigned to '+[...new Set(who)].join(', ')+'.':'');
let s;if(prev)s=K.edgeStep(K.link(prev,h,{arrow:true}),{auto,title:c.text,chip:cs.length+''});else{s=K.nodeStep(h,{auto});s.chip=cs.length+''}
s.nodes=[...(prev?[prev.id]:[]),h.id,...cs.map(x=>x.n.id)];steps.push(s);prev=h;
});
const N=[...K.nodes.values()];routeFixed(N,K.links);
return {type:'kanban',nodes:N,links:K.links,steps,groups:K.groups,fixed:true};
}
/* ---------- mermaid: packet ---------- */
/** @param {string[]} ls @returns {Graph} */
export function parsePacket(ls){
let title='',next=0;const f=[];
for(const line of ls){let m;
if(m=line.match(/^title\s+(.+)$/)){title=cleanText(m[1]);continue}
if(m=line.match(/^(\d+)(?:\s*-\s*(\d+))?\s*:\s*(.+)$/)){const a=+m[1],b=m[2]!=null?+m[2]:a;f.push({a,b,label:cleanText(m[3])});next=b+1;continue}
if(m=line.match(/^\+(\d+)\s*:\s*(.+)$/)){const a=next,b=next+Math.max(1,+m[1])-1;f.push({a,b,label:cleanText(m[2])});next=b+1}
}
if(!f.length)throw new Error('No fields found in the packet diagram. Write them like 0-15: "Source Port"');
const W=32,groups=/** @type {Group[]} */([]),rowIx=/** @type {Map<number,number>} */(new Map()),count=/** @type {Map<number,number>} */(new Map()),mx=Math.max(...f.map(x=>x.b-x.a+1));
const nodes=f.map((x,i)=>{const r=Math.floor(x.a/W);if(!rowIx.has(r)){groups.push({title:'Bits '+r*W+'–'+(r*W+W-1)});rowIx.set(r,groups.length-1)}
const k=count.get(r)||0;count.set(r,k+1);const bits=x.b-x.a+1;
return {id:'f'+(i+1),label:x.label,shape:bits===1?'circle':'box',group:rowIx.get(r)??null,gx:k*DX,gy:(rowIx.get(r)||0)*2.9,hk:bits===1?1:.5+1.5*Math.log2(bits)/Math.log2(Math.max(2,mx)),
note:(bits===1?'Bit '+x.a:'Bits '+x.a+'–'+x.b)+' ('+bits+' bit'+(bits===1?'':'s')+(bits%8===0?', '+bits/8+' byte'+(bits===8?'':'s'):'')+').'}});
const B=(/** @type {string} */s)=>'**'+s+'**';
const steps=f.map((x,i)=>{const bits=x.b-x.a+1,n=nodes[i];
const auto=bits===1?'Bit '+B(String(x.a))+' is '+B(x.label)+', a single on/off flag.':
(i===0?'The message starts with ':'Next, bits ')+(i===0?B(x.label)+' in bits '+B(x.a+'–'+x.b):B(x.a+'–'+x.b)+' hold '+B(x.label))+' ('+bits+' bits'+(bits%8===0?', '+bits/8+' byte'+(bits===8?'':'s'):'')+').';
return {kind:'node',nodes:[n.id],title:x.label,chip:bits+' bit'+(bits===1?'':'s'),auto,tag:groups[/** @type {number} */(n.group)].title}});