forked from mendixlabs/mxcli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd_microflows_show.go
More file actions
1150 lines (1008 loc) · 34.1 KB
/
cmd_microflows_show.go
File metadata and controls
1150 lines (1008 loc) · 34.1 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
// SPDX-License-Identifier: Apache-2.0
// Package executor - Microflow SHOW/DESCRIBE commands
package executor
import (
"fmt"
"sort"
"strings"
"github.com/mendixlabs/mxcli/mdl/ast"
mdlerrors "github.com/mendixlabs/mxcli/mdl/errors"
"github.com/mendixlabs/mxcli/model"
"github.com/mendixlabs/mxcli/sdk/microflows"
)
// listMicroflows handles SHOW MICROFLOWS command.
func listMicroflows(ctx *ExecContext, moduleName string) error {
// Get hierarchy for module/folder resolution
h, err := getHierarchy(ctx)
if err != nil {
return mdlerrors.NewBackend("build hierarchy", err)
}
// Validate module exists if specified
if moduleName != "" {
if _, err := findModule(ctx, moduleName); err != nil {
return err
}
}
// Get all microflows
microflows, err := ctx.Backend.ListMicroflows()
if err != nil {
return mdlerrors.NewBackend("list microflows", err)
}
// Collect rows and calculate column widths
type row struct {
qualifiedName string
module string
name string
excluded bool
folderPath string
params int
activities int
complexity int
returnType string
}
var rows []row
for _, mf := range microflows {
modID := h.FindModuleID(mf.ContainerID)
modName := h.GetModuleName(modID)
if moduleName == "" || modName == moduleName {
qualifiedName := modName + "." + mf.Name
folderPath := h.BuildFolderPath(mf.ContainerID)
returnType := ""
if mf.ReturnType != nil {
returnType = mf.ReturnType.GetTypeName()
}
// Count activities (excluding structural elements like Start/End events)
activityCount := countMicroflowActivities(mf)
// Calculate McCabe cyclomatic complexity
complexity := calculateMicroflowComplexity(mf)
rows = append(rows, row{qualifiedName, modName, mf.Name, mf.Excluded, folderPath, len(mf.Parameters), activityCount, complexity, returnType})
}
}
// Sort by qualified name
sort.Slice(rows, func(i, j int) bool {
return strings.ToLower(rows[i].qualifiedName) < strings.ToLower(rows[j].qualifiedName)
})
result := &TableResult{
Columns: []string{"Qualified Name", "Module", "Name", "Excluded", "Folder", "Params", "Actions", "McCabe", "Returns"},
Summary: fmt.Sprintf("(%d microflows)", len(rows)),
}
for _, r := range rows {
result.Rows = append(result.Rows, []any{r.qualifiedName, r.module, r.name, r.excluded, r.folderPath, r.params, r.activities, r.complexity, r.returnType})
}
return writeResult(ctx, result)
}
// listNanoflows handles SHOW NANOFLOWS command.
func listNanoflows(ctx *ExecContext, moduleName string) error {
// Get hierarchy for module/folder resolution
h, err := getHierarchy(ctx)
if err != nil {
return mdlerrors.NewBackend("build hierarchy", err)
}
// Validate module exists if specified
if moduleName != "" {
if _, err := findModule(ctx, moduleName); err != nil {
return err
}
}
// Get all nanoflows
nanoflows, err := ctx.Backend.ListNanoflows()
if err != nil {
return mdlerrors.NewBackend("list nanoflows", err)
}
// Collect rows and calculate column widths
type row struct {
qualifiedName string
module string
name string
excluded bool
folderPath string
params int
activities int
complexity int
returnType string
}
var rows []row
for _, nf := range nanoflows {
modID := h.FindModuleID(nf.ContainerID)
modName := h.GetModuleName(modID)
if moduleName == "" || modName == moduleName {
qualifiedName := modName + "." + nf.Name
folderPath := h.BuildFolderPath(nf.ContainerID)
returnType := ""
if nf.ReturnType != nil {
returnType = nf.ReturnType.GetTypeName()
}
// Count activities (excluding structural elements like Start/End events)
activityCount := countNanoflowActivities(nf)
// Calculate McCabe cyclomatic complexity
complexity := calculateNanoflowComplexity(nf)
rows = append(rows, row{qualifiedName, modName, nf.Name, nf.Excluded, folderPath, len(nf.Parameters), activityCount, complexity, returnType})
}
}
// Sort by qualified name
sort.Slice(rows, func(i, j int) bool {
return strings.ToLower(rows[i].qualifiedName) < strings.ToLower(rows[j].qualifiedName)
})
result := &TableResult{
Columns: []string{"Qualified Name", "Module", "Name", "Excluded", "Folder", "Params", "Actions", "McCabe", "Returns"},
Summary: fmt.Sprintf("(%d nanoflows)", len(rows)),
}
for _, r := range rows {
result.Rows = append(result.Rows, []any{r.qualifiedName, r.module, r.name, r.excluded, r.folderPath, r.params, r.activities, r.complexity, r.returnType})
}
return writeResult(ctx, result)
}
// countNanoflowActivities counts meaningful activities in a nanoflow.
func countNanoflowActivities(nf *microflows.Nanoflow) int {
if nf.ObjectCollection == nil {
return 0
}
count := 0
for _, obj := range nf.ObjectCollection.Objects {
switch obj.(type) {
case *microflows.StartEvent, *microflows.EndEvent, *microflows.ExclusiveMerge:
// Skip structural elements
default:
count++
}
}
return count
}
// calculateNanoflowComplexity calculates McCabe cyclomatic complexity for a nanoflow.
func calculateNanoflowComplexity(nf *microflows.Nanoflow) int {
if nf.ObjectCollection == nil {
return 1
}
// McCabe = E - N + 2P where E = edges, N = nodes, P = connected components (1 for a single flow)
// Simplified: 1 + number of decision points (ExclusiveSplit, InheritanceSplit, LoopedActivity)
complexity := 1
for _, obj := range nf.ObjectCollection.Objects {
switch obj.(type) {
case *microflows.ExclusiveSplit, *microflows.InheritanceSplit, *microflows.LoopedActivity:
complexity++
}
}
return complexity
}
// describeMicroflow handles DESCRIBE MICROFLOW command - outputs MDL source code.
func describeMicroflow(ctx *ExecContext, name ast.QualifiedName) error {
// Get hierarchy for module/folder resolution
h, err := getHierarchy(ctx)
if err != nil {
return mdlerrors.NewBackend("build hierarchy", err)
}
// Use pre-warmed cache if available (from PreWarmCache), otherwise build on demand
entityNames := getEntityNames(ctx, h)
microflowNames := getMicroflowNames(ctx, h)
// Find the microflow
allMicroflows, err := ctx.Backend.ListMicroflows()
if err != nil {
return mdlerrors.NewBackend("list microflows", err)
}
// Supplement microflow name lookup if not pre-warmed
if len(microflowNames) == 0 {
for _, mf := range allMicroflows {
microflowNames[mf.ID] = h.GetQualifiedName(mf.ContainerID, mf.Name)
}
}
var targetMf *microflows.Microflow
for _, mf := range allMicroflows {
modID := h.FindModuleID(mf.ContainerID)
modName := h.GetModuleName(modID)
if modName == name.Module && mf.Name == name.Name {
targetMf = mf
break
}
}
if targetMf == nil {
return mdlerrors.NewNotFound("microflow", name.String())
}
// Generate MDL output
var lines []string
// Documentation
if targetMf.Documentation != "" {
lines = append(lines, "/**")
for docLine := range strings.SplitSeq(targetMf.Documentation, "\n") {
lines = append(lines, " * "+docLine)
}
lines = append(lines, " */")
}
// @excluded annotation
if targetMf.Excluded {
lines = append(lines, "@excluded")
}
// CREATE MICROFLOW header
qualifiedName := name.Module + "." + name.Name
if len(targetMf.Parameters) > 0 {
lines = append(lines, fmt.Sprintf("create or modify microflow %s (", qualifiedName))
for i, param := range targetMf.Parameters {
paramType := "Object"
if param.Type != nil {
paramType = formatMicroflowDataType(ctx, param.Type, entityNames)
}
comma := ","
if i == len(targetMf.Parameters)-1 {
comma = ""
}
lines = append(lines, fmt.Sprintf(" $%s: %s%s", param.Name, paramType, comma))
}
lines = append(lines, ")")
} else {
lines = append(lines, fmt.Sprintf("create or modify microflow %s ()", qualifiedName))
}
// Return type
if targetMf.ReturnType != nil {
returnType := formatMicroflowDataType(ctx, targetMf.ReturnType, entityNames)
if returnType != "Void" && returnType != "" {
returnLine := fmt.Sprintf("returns %s", returnType)
// Add variable name if specified (AS $VarName)
if targetMf.ReturnVariableName != "" && targetMf.ReturnVariableName != "Variable" {
returnLine += fmt.Sprintf(" as $%s", targetMf.ReturnVariableName)
}
lines = append(lines, returnLine)
}
}
// Folder
if folderPath := h.BuildFolderPath(targetMf.ContainerID); folderPath != "" {
lines = append(lines, fmt.Sprintf("folder %s", mdlQuote(folderPath)))
}
// BEGIN block
lines = append(lines, "begin")
prevDescribingReturnValue := ctx.DescribingMicroflowHasReturnValue
ctx.DescribingMicroflowHasReturnValue = microflowHasReturnValue(targetMf)
defer func() {
ctx.DescribingMicroflowHasReturnValue = prevDescribingReturnValue
}()
// Generate activities
if targetMf.ObjectCollection != nil && len(targetMf.ObjectCollection.Objects) > 0 {
activityLines := formatMicroflowActivities(ctx, targetMf, entityNames, microflowNames)
activityLines = prependFreeAnnotationLines(targetMf.ObjectCollection, activityLines)
for _, line := range activityLines {
lines = append(lines, " "+line)
}
} else {
lines = append(lines, " -- No activities")
}
lines = append(lines, "end;")
// Add GRANT EXECUTE if roles are assigned
if len(targetMf.AllowedModuleRoles) > 0 {
roles := make([]string, len(targetMf.AllowedModuleRoles))
for i, r := range targetMf.AllowedModuleRoles {
roles[i] = string(r)
}
lines = append(lines, "")
lines = append(lines, fmt.Sprintf("grant execute on microflow %s.%s to %s;",
name.Module, name.Name, strings.Join(roles, ", ")))
}
lines = append(lines, "/")
// Output
fmt.Fprintln(ctx.Output, strings.Join(lines, "\n"))
return nil
}
// describeNanoflow generates re-executable CREATE OR MODIFY NANOFLOW MDL output
// with activities and control flows listed as comments.
func describeNanoflow(ctx *ExecContext, name ast.QualifiedName) error {
h, err := getHierarchy(ctx)
if err != nil {
return mdlerrors.NewBackend("build hierarchy", err)
}
// Build entity name lookup
entityNames := make(map[model.ID]string)
domainModels, err := ctx.Backend.ListDomainModels()
if err != nil {
return mdlerrors.NewBackend("list domain models", err)
}
for _, dm := range domainModels {
modName := h.GetModuleName(dm.ContainerID)
for _, entity := range dm.Entities {
entityNames[entity.ID] = modName + "." + entity.Name
}
}
// Build microflow/nanoflow name lookup (used for call actions)
microflowNames := make(map[model.ID]string)
allMicroflows, err := ctx.Backend.ListMicroflows()
if err != nil {
return mdlerrors.NewBackend("list microflows", err)
}
for _, mf := range allMicroflows {
microflowNames[mf.ID] = h.GetQualifiedName(mf.ContainerID, mf.Name)
}
// Find the nanoflow
allNanoflows, err := ctx.Backend.ListNanoflows()
if err != nil {
return mdlerrors.NewBackend("list nanoflows", err)
}
for _, nf := range allNanoflows {
microflowNames[nf.ID] = h.GetQualifiedName(nf.ContainerID, nf.Name)
}
var targetNf *microflows.Nanoflow
for _, nf := range allNanoflows {
modID := h.FindModuleID(nf.ContainerID)
modName := h.GetModuleName(modID)
if modName == name.Module && nf.Name == name.Name {
targetNf = nf
break
}
}
if targetNf == nil {
return mdlerrors.NewNotFound("nanoflow", name.String())
}
var lines []string
// Documentation
if targetNf.Documentation != "" {
lines = append(lines, "/**")
for docLine := range strings.SplitSeq(targetNf.Documentation, "\n") {
lines = append(lines, " * "+docLine)
}
lines = append(lines, " */")
}
// CREATE NANOFLOW header
qualifiedName := name.Module + "." + name.Name
if len(targetNf.Parameters) > 0 {
lines = append(lines, fmt.Sprintf("create or modify nanoflow %s (", qualifiedName))
for i, param := range targetNf.Parameters {
paramType := "Object"
if param.Type != nil {
paramType = formatMicroflowDataType(ctx, param.Type, entityNames)
}
comma := ","
if i == len(targetNf.Parameters)-1 {
comma = ""
}
lines = append(lines, fmt.Sprintf(" $%s: %s%s", param.Name, paramType, comma))
}
lines = append(lines, ")")
} else {
lines = append(lines, fmt.Sprintf("create or modify nanoflow %s ()", qualifiedName))
}
// Return type
if targetNf.ReturnType != nil {
returnType := formatMicroflowDataType(ctx, targetNf.ReturnType, entityNames)
if returnType != "Void" && returnType != "" {
lines = append(lines, fmt.Sprintf("returns %s", returnType))
}
}
// Folder
if folderPath := h.BuildFolderPath(targetNf.ContainerID); folderPath != "" {
lines = append(lines, fmt.Sprintf("folder %s", mdlQuote(folderPath)))
}
// BEGIN block with activities
lines = append(lines, "begin")
// Wrap nanoflow in a Microflow to reuse formatMicroflowActivities
if targetNf.ObjectCollection != nil && len(targetNf.ObjectCollection.Objects) > 0 {
wrapperMf := µflows.Microflow{
ObjectCollection: targetNf.ObjectCollection,
}
activityLines := formatMicroflowActivities(ctx, wrapperMf, entityNames, microflowNames)
for _, line := range activityLines {
lines = append(lines, " "+line)
}
} else {
lines = append(lines, " -- No activities")
}
lines = append(lines, "end;")
lines = append(lines, "/")
fmt.Fprintln(ctx.Output, strings.Join(lines, "\n"))
return nil
}
// describeMicroflowToString generates MDL source for a microflow and returns it as a string
// along with a source map mapping node IDs to line ranges.
func describeMicroflowToString(ctx *ExecContext, name ast.QualifiedName) (string, map[string]elkSourceRange, error) {
h, err := getHierarchy(ctx)
if err != nil {
return "", nil, mdlerrors.NewBackend("build hierarchy", err)
}
entityNames := make(map[model.ID]string)
domainModels, _ := ctx.Backend.ListDomainModels()
for _, dm := range domainModels {
modName := h.GetModuleName(dm.ContainerID)
for _, entity := range dm.Entities {
entityNames[entity.ID] = modName + "." + entity.Name
}
}
microflowNames := make(map[model.ID]string)
allMicroflows, err := ctx.Backend.ListMicroflows()
if err != nil {
return "", nil, mdlerrors.NewBackend("list microflows", err)
}
for _, mf := range allMicroflows {
microflowNames[mf.ID] = h.GetQualifiedName(mf.ContainerID, mf.Name)
}
var targetMf *microflows.Microflow
for _, mf := range allMicroflows {
modID := h.FindModuleID(mf.ContainerID)
modName := h.GetModuleName(modID)
if modName == name.Module && mf.Name == name.Name {
targetMf = mf
break
}
}
if targetMf == nil {
return "", nil, mdlerrors.NewNotFound("microflow", name.String())
}
sourceMap := make(map[string]elkSourceRange)
mdl := renderMicroflowMDL(ctx, "microflow", targetMf, name, entityNames, microflowNames, sourceMap)
return mdl, sourceMap, nil
}
// describeNanoflowToString generates MDL source for a nanoflow and returns it as a string
// along with a source map mapping node IDs to line ranges.
func describeNanoflowToString(ctx *ExecContext, name ast.QualifiedName) (string, map[string]elkSourceRange, error) {
h, err := getHierarchy(ctx)
if err != nil {
return "", nil, mdlerrors.NewBackend("build hierarchy", err)
}
entityNames := make(map[model.ID]string)
domainModels, err := ctx.Backend.ListDomainModels()
if err != nil {
return "", nil, mdlerrors.NewBackend("list domain models", err)
}
for _, dm := range domainModels {
modName := h.GetModuleName(dm.ContainerID)
for _, entity := range dm.Entities {
entityNames[entity.ID] = modName + "." + entity.Name
}
}
microflowNames := make(map[model.ID]string)
allMicroflows, err := ctx.Backend.ListMicroflows()
if err != nil {
return "", nil, mdlerrors.NewBackend("list microflows", err)
}
for _, mf := range allMicroflows {
microflowNames[mf.ID] = h.GetQualifiedName(mf.ContainerID, mf.Name)
}
allNanoflows, err := ctx.Backend.ListNanoflows()
if err != nil {
return "", nil, mdlerrors.NewBackend("list nanoflows", err)
}
for _, nf := range allNanoflows {
microflowNames[nf.ID] = h.GetQualifiedName(nf.ContainerID, nf.Name)
}
var targetNf *microflows.Nanoflow
for _, nf := range allNanoflows {
modID := h.FindModuleID(nf.ContainerID)
modName := h.GetModuleName(modID)
if modName == name.Module && nf.Name == name.Name {
targetNf = nf
break
}
}
if targetNf == nil {
return "", nil, mdlerrors.NewNotFound("nanoflow", name.String())
}
// Wrap nanoflow as a Microflow so renderMicroflowMDL can handle it
wrapperMf := µflows.Microflow{
Documentation: targetNf.Documentation,
Excluded: targetNf.Excluded,
Parameters: targetNf.Parameters,
ReturnType: targetNf.ReturnType,
ObjectCollection: targetNf.ObjectCollection,
AllowedModuleRoles: targetNf.AllowedModuleRoles,
}
sourceMap := make(map[string]elkSourceRange)
mdl := renderMicroflowMDL(ctx, "nanoflow", wrapperMf, name, entityNames, microflowNames, sourceMap)
return mdl, sourceMap, nil
}
// renderMicroflowMDL formats a parsed Microflow as MDL text.
//
// Shared by DESCRIBE MICROFLOW and `diff-local`, so both paths produce the
// same output. entityNames/microflowNames provide ID → qualified-name
// resolution; pass empty maps if unavailable (types will fall back to
// "Object"/"List" stubs). If sourceMap is non-nil it will be populated with
// ELK node IDs → line ranges for visualization; pass nil when not needed.
func renderMicroflowMDL(
ctx *ExecContext,
flowType string,
mf *microflows.Microflow,
name ast.QualifiedName,
entityNames map[model.ID]string,
microflowNames map[model.ID]string,
sourceMap map[string]elkSourceRange,
) string {
prevDescribingReturnValue := ctx.DescribingMicroflowHasReturnValue
ctx.DescribingMicroflowHasReturnValue = microflowHasReturnValue(mf)
defer func() {
ctx.DescribingMicroflowHasReturnValue = prevDescribingReturnValue
}()
var lines []string
if mf.Documentation != "" {
lines = append(lines, "/**")
for docLine := range strings.SplitSeq(mf.Documentation, "\n") {
lines = append(lines, " * "+docLine)
}
lines = append(lines, " */")
}
if mf.Excluded {
lines = append(lines, "@excluded")
}
qualifiedName := name.Module + "." + name.Name
if len(mf.Parameters) > 0 {
lines = append(lines, fmt.Sprintf("create or modify %s %s (", flowType, qualifiedName))
for i, param := range mf.Parameters {
paramType := "Object"
if param.Type != nil {
paramType = formatMicroflowDataType(ctx, param.Type, entityNames)
}
comma := ","
if i == len(mf.Parameters)-1 {
comma = ""
}
lines = append(lines, fmt.Sprintf(" $%s: %s%s", param.Name, paramType, comma))
}
lines = append(lines, ")")
} else {
lines = append(lines, fmt.Sprintf("create or modify %s %s ()", flowType, qualifiedName))
}
if mf.ReturnType != nil {
returnType := formatMicroflowDataType(ctx, mf.ReturnType, entityNames)
if returnType != "Void" && returnType != "" {
returnLine := fmt.Sprintf("returns %s", returnType)
if mf.ReturnVariableName != "" && mf.ReturnVariableName != "Variable" {
returnLine += fmt.Sprintf(" as $%s", mf.ReturnVariableName)
}
lines = append(lines, returnLine)
}
}
lines = append(lines, "begin")
headerLineCount := len(lines)
if mf.ObjectCollection != nil && len(mf.ObjectCollection.Objects) > 0 {
var activityLines []string
if sourceMap != nil {
activityLines = formatMicroflowActivitiesWithSourceMap(ctx, mf, entityNames, microflowNames, sourceMap, headerLineCount)
} else {
activityLines = formatMicroflowActivities(ctx, mf, entityNames, microflowNames)
}
activityLines = prependFreeAnnotationLines(mf.ObjectCollection, activityLines)
for _, line := range activityLines {
lines = append(lines, " "+line)
}
} else {
lines = append(lines, " -- No activities")
}
lines = append(lines, "end;")
if len(mf.AllowedModuleRoles) > 0 {
roles := make([]string, len(mf.AllowedModuleRoles))
for i, r := range mf.AllowedModuleRoles {
roles[i] = string(r)
}
lines = append(lines, "")
lines = append(lines, fmt.Sprintf("grant execute on %s %s.%s to %s;",
flowType, name.Module, name.Name, strings.Join(roles, ", ")))
}
lines = append(lines, "/")
return strings.Join(lines, "\n")
}
func microflowHasReturnValue(mf *microflows.Microflow) bool {
if mf == nil || mf.ReturnType == nil {
return false
}
_, isVoid := mf.ReturnType.(*microflows.VoidType)
return !isVoid
}
// formatMicroflowDataType formats a microflow data type for MDL output.
func formatMicroflowDataType(ctx *ExecContext, dt microflows.DataType, entityNames map[model.ID]string) string {
if dt == nil {
return "Unknown"
}
switch t := dt.(type) {
case *microflows.BooleanType:
return "Boolean"
case *microflows.IntegerType:
return "Integer"
case *microflows.LongType:
return "Long"
case *microflows.DecimalType:
return "Decimal"
case *microflows.StringType:
return "String"
case *microflows.DateTimeType:
return "DateTime"
case *microflows.DateType:
return "Date"
case *microflows.BinaryType:
return "Binary"
case *microflows.VoidType:
return "Void"
case *microflows.ObjectType:
// First try EntityQualifiedName (BY_NAME_REFERENCE), then fall back to EntityID lookup
if t.EntityQualifiedName != "" {
return t.EntityQualifiedName
}
if name, ok := entityNames[t.EntityID]; ok {
return name
}
return "Object"
case *microflows.ListType:
// First try EntityQualifiedName (BY_NAME_REFERENCE), then fall back to EntityID lookup
if t.EntityQualifiedName != "" {
return "List of " + t.EntityQualifiedName
}
if name, ok := entityNames[t.EntityID]; ok {
return "List of " + name
}
return "List"
case *microflows.EnumerationType:
if t.EnumerationQualifiedName != "" {
return "enum " + t.EnumerationQualifiedName
}
return "Enumeration"
default:
return dt.GetTypeName()
}
}
// formatMicroflowActivities generates MDL statements for microflow activities.
func formatMicroflowActivities(
ctx *ExecContext,
mf *microflows.Microflow,
entityNames map[model.ID]string,
microflowNames map[model.ID]string,
) []string {
if mf.ObjectCollection == nil {
return []string{"-- debug: ObjectCollection is nil"}
}
// Build activity map by ID for flow traversal
activityMap := make(map[model.ID]microflows.MicroflowObject)
var startID model.ID
for _, obj := range mf.ObjectCollection.Objects {
activityMap[obj.GetID()] = obj
if _, ok := obj.(*microflows.StartEvent); ok {
startID = obj.GetID()
}
}
// Build flow graph: map from origin ID to flows (sorted by OriginConnectionIndex).
// Build the inverse destination→flows map for @anchor emission.
flowsByOrigin := make(map[model.ID][]*microflows.SequenceFlow)
flowsByDest := make(map[model.ID][]*microflows.SequenceFlow)
for _, flow := range mf.ObjectCollection.Flows {
flowsByOrigin[flow.OriginID] = append(flowsByOrigin[flow.OriginID], flow)
flowsByDest[flow.DestinationID] = append(flowsByDest[flow.DestinationID], flow)
}
var lines []string
lines = append(lines, duplicateOutputVariableWarnings(mf.ObjectCollection)...)
// Sort flows by OriginConnectionIndex for each origin
for originID := range flowsByOrigin {
flows := flowsByOrigin[originID]
// Simple bubble sort since typically only 2 flows per split
for i := 0; i < len(flows)-1; i++ {
for j := i + 1; j < len(flows); j++ {
if flows[i].OriginConnectionIndex > flows[j].OriginConnectionIndex {
flows[i], flows[j] = flows[j], flows[i]
}
}
}
}
// Find the merge point for each split (where branches converge)
splitMergeMap := findSplitMergePoints(ctx, mf.ObjectCollection, activityMap)
// Traverse the flow graph recursively
visited := make(map[model.ID]bool)
// Build annotation map for @annotation emission
annotationsByTarget := buildAnnotationsByTarget(mf.ObjectCollection)
// flowsByOrigin / flowsByDest are threaded into traverseFlow so @anchor
// emission is per-call — no package-level globals, safe under concurrent
// describe (e.g. captureDescribeParallel).
traverseFlow(ctx, startID, activityMap, flowsByOrigin, flowsByDest, splitMergeMap, visited, entityNames, microflowNames, &lines, 0, nil, 0, annotationsByTarget)
return lines
}
type outputVariableSeen struct {
pos model.Point
}
func duplicateOutputVariableWarnings(oc *microflows.MicroflowObjectCollection) []string {
warningPositions := make(map[string]model.Point)
var walkCollection func(*microflows.MicroflowObjectCollection, map[string]outputVariableSeen)
walkCollection = func(collection *microflows.MicroflowObjectCollection, inherited map[string]outputVariableSeen) {
if collection == nil {
return
}
activityMap := make(map[model.ID]microflows.MicroflowObject)
flowsByOrigin := make(map[model.ID][]*microflows.SequenceFlow)
var starts []model.ID
for _, obj := range collection.Objects {
activityMap[obj.GetID()] = obj
if _, ok := obj.(*microflows.StartEvent); ok {
starts = append(starts, obj.GetID())
}
}
for _, flow := range collection.Flows {
flowsByOrigin[flow.OriginID] = append(flowsByOrigin[flow.OriginID], flow)
}
if len(starts) == 0 {
for _, obj := range collection.Objects {
starts = append(starts, obj.GetID())
}
}
var walkNode func(model.ID, map[string]outputVariableSeen, map[model.ID]bool)
walkNode = func(currentID model.ID, seen map[string]outputVariableSeen, path map[model.ID]bool) {
if currentID == "" || path[currentID] {
return
}
obj := activityMap[currentID]
if obj == nil {
return
}
path = cloneIDBoolMap(path)
path[currentID] = true
seen = cloneSeenOutputs(seen)
if activity, ok := obj.(*microflows.ActionActivity); ok {
if name := actionOutputVariableName(activity.Action); name != "" {
if first, ok := seen[name]; ok {
if _, recorded := warningPositions[name]; !recorded {
warningPositions[name] = first.pos
}
} else {
seen[name] = outputVariableSeen{pos: obj.GetPosition()}
}
}
}
if loop, ok := obj.(*microflows.LoopedActivity); ok {
walkCollection(loop.ObjectCollection, seen)
}
for _, flow := range findNormalFlows(flowsByOrigin[currentID]) {
walkNode(flow.DestinationID, seen, path)
}
}
for _, startID := range starts {
walkNode(startID, cloneSeenOutputs(inherited), nil)
}
}
walkCollection(oc, nil)
var names []string
for name := range warningPositions {
names = append(names, name)
}
sort.Strings(names)
warnings := make([]string, 0, len(names))
for _, name := range names {
pos := warningPositions[name]
warnings = append(warnings, fmt.Sprintf("-- WARNING: duplicate output variable $%s at position (%d, %d) - model is invalid; open in Studio Pro to fix", name, pos.X, pos.Y))
}
return warnings
}
func cloneSeenOutputs(src map[string]outputVariableSeen) map[string]outputVariableSeen {
if src == nil {
return make(map[string]outputVariableSeen)
}
dst := make(map[string]outputVariableSeen, len(src))
for k, v := range src {
dst[k] = v
}
return dst
}
func cloneIDBoolMap(src map[model.ID]bool) map[model.ID]bool {
if src == nil {
return make(map[model.ID]bool)
}
dst := make(map[model.ID]bool, len(src))
for k, v := range src {
dst[k] = v
}
return dst
}
func actionOutputVariableName(action any) string {
switch a := action.(type) {
case *microflows.CreateObjectAction:
return a.OutputVariable
case *microflows.RetrieveAction:
return a.OutputVariable
case *microflows.JavaActionCallAction:
if a.UseReturnVariable {
return a.ResultVariableName
}
case *microflows.MicroflowCallAction:
if a.UseReturnVariable {
return a.ResultVariableName
}
case *microflows.NanoflowCallAction:
if a.UseReturnVariable {
return a.OutputVariableName
}
case *microflows.JavaScriptActionCallAction:
if a.UseReturnVariable {
return a.OutputVariableName
}
case *microflows.AggregateListAction:
return a.OutputVariable
case *microflows.ListOperationAction:
return a.OutputVariable
case *microflows.RestCallAction:
return a.OutputVariable
case *microflows.ImportMappingCallAction:
return a.OutputVariable
case *microflows.ExportMappingCallAction:
return a.OutputVariable
case *microflows.CallExternalAction:
if a.UseReturnVariable {
return a.ResultVariableName
}
}
return ""
}
// formatMicroflowActivitiesWithSourceMap generates MDL statements and populates a source map
// mapping ELK node IDs ("node-<objectID>") to line ranges (0-indexed) in the full MDL output.
// headerLineCount is the number of lines before the BEGIN body (to compute absolute line numbers).
func formatMicroflowActivitiesWithSourceMap(
ctx *ExecContext,
mf *microflows.Microflow,
entityNames map[model.ID]string,
microflowNames map[model.ID]string,
sourceMap map[string]elkSourceRange,
headerLineCount int,
) []string {
if mf.ObjectCollection == nil {
return []string{"-- debug: ObjectCollection is nil"}
}
activityMap := make(map[model.ID]microflows.MicroflowObject)
var startID model.ID
for _, obj := range mf.ObjectCollection.Objects {
activityMap[obj.GetID()] = obj
if _, ok := obj.(*microflows.StartEvent); ok {
startID = obj.GetID()
}
}
flowsByOrigin := make(map[model.ID][]*microflows.SequenceFlow)
flowsByDest := make(map[model.ID][]*microflows.SequenceFlow)
for _, flow := range mf.ObjectCollection.Flows {
flowsByOrigin[flow.OriginID] = append(flowsByOrigin[flow.OriginID], flow)
flowsByDest[flow.DestinationID] = append(flowsByDest[flow.DestinationID], flow)
}
var lines []string
lines = append(lines, duplicateOutputVariableWarnings(mf.ObjectCollection)...)
for originID := range flowsByOrigin {
flows := flowsByOrigin[originID]
for i := 0; i < len(flows)-1; i++ {
for j := i + 1; j < len(flows); j++ {
if flows[i].OriginConnectionIndex > flows[j].OriginConnectionIndex {
flows[i], flows[j] = flows[j], flows[i]
}
}
}
}
splitMergeMap := findSplitMergePoints(ctx, mf.ObjectCollection, activityMap)
visited := make(map[model.ID]bool)
// Build annotation map for @annotation emission
annotationsByTarget := buildAnnotationsByTarget(mf.ObjectCollection)
traverseFlow(ctx, startID, activityMap, flowsByOrigin, flowsByDest, splitMergeMap, visited, entityNames, microflowNames, &lines, 0, sourceMap, headerLineCount, annotationsByTarget)
return lines
}
// findSplitMergePoints finds the corresponding merge point for each exclusive split.
func findSplitMergePoints(
ctx *ExecContext,
oc *microflows.MicroflowObjectCollection,
activityMap map[model.ID]microflows.MicroflowObject,
) map[model.ID]model.ID {
// Build flow graph for forward traversal
flowsByOrigin := make(map[model.ID][]*microflows.SequenceFlow)
for _, flow := range oc.Flows {
flowsByOrigin[flow.OriginID] = append(flowsByOrigin[flow.OriginID], flow)
}
return findSplitMergePointsForGraph(ctx, activityMap, flowsByOrigin)
}