forked from pontasan/staruml-controller
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-handler.js
More file actions
7800 lines (6988 loc) · 266 KB
/
api-handler.js
File metadata and controls
7800 lines (6988 loc) · 266 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
/**
* REST API Handler for StarUML Controller
*
* Provides CRUD operations for ERD elements with input validation
* and detailed request/response logging.
*/
const ddlGenerator = require('./ddl-generator')
const crudFactory = require('./handlers/crud-factory')
const { autoExpandFrame, fitFrameToViews, clearEdgeWaypoints } = require('./handlers/shared-helpers')
// ============================================================
// Family Configs & Routers
// ============================================================
const familyConfigs = [
require('./handlers/family-class'),
require('./handlers/family-usecase'),
require('./handlers/family-activity'),
require('./handlers/family-statemachine'),
require('./handlers/family-component'),
require('./handlers/family-deployment'),
require('./handlers/family-object'),
require('./handlers/family-communication'),
require('./handlers/family-composite'),
require('./handlers/family-infoflow'),
require('./handlers/family-profile'),
require('./handlers/family-timing'),
require('./handlers/family-overview'),
require('./handlers/family-flowchart'),
require('./handlers/family-dfd'),
require('./handlers/family-bpmn'),
require('./handlers/family-c4'),
require('./handlers/family-sysml'),
require('./handlers/family-wireframe'),
require('./handlers/family-mindmap'),
require('./handlers/family-aws'),
require('./handlers/family-azure'),
require('./handlers/family-gcp')
]
const familyRouters = familyConfigs.map(function (config) {
return crudFactory.createRouter(config)
})
// Collect all family endpoints for /api/status
const familyEndpoints = []
familyConfigs.forEach(function (config) {
const eps = crudFactory.getEndpointList(config)
eps.forEach(function (ep) {
familyEndpoints.push(ep)
})
})
// ============================================================
// Constants
// ============================================================
// --- Sequence Diagram Constants ---
const VALID_MESSAGE_SORTS = [
'synchCall', 'asynchCall', 'asynchSignal', 'createMessage', 'deleteMessage', 'reply'
]
const VALID_INTERACTION_OPERATORS = [
'alt', 'opt', 'par', 'loop', 'critical', 'neg', 'assert', 'strict', 'seq', 'ignore', 'consider', 'break'
]
// --- ERD Constants ---
const ALLOWED_COLUMN_TYPES = [
'CHAR', 'VARCHAR', 'TEXT', 'CLOB',
'BOOLEAN',
'SMALLINT', 'INTEGER', 'INT', 'BIGINT', 'TINYINT',
'FLOAT', 'DOUBLE', 'REAL', 'DECIMAL', 'NUMERIC',
'DATE', 'TIME', 'DATETIME', 'TIMESTAMP',
'BLOB', 'BINARY', 'VARBINARY',
'UUID', 'JSON', 'JSONB', 'XML',
'SERIAL', 'BIGSERIAL'
]
const VALID_TAG_KINDS = [0, 1, 2, 3, 4]
const TAG_KIND_LABELS = {
0: 'string', 1: 'boolean', 2: 'number', 3: 'reference', 4: 'hidden'
}
const SEQUENCE_PREFIX = 'sequence#'
const INDEX_PREFIX = 'index#'
const SEQUENCE_ALLOWED_FIELDS = ['name']
const INDEX_ALLOWED_FIELDS = ['name', 'definition']
// --- Generic Diagram Constants ---
const ALLOWED_DIAGRAM_TYPES = [
// UML
'UMLClassDiagram', 'UMLPackageDiagram', 'UMLObjectDiagram',
'UMLComponentDiagram', 'UMLDeploymentDiagram', 'UMLUseCaseDiagram',
'UMLStatechartDiagram', 'UMLActivityDiagram', 'UMLCommunicationDiagram',
'UMLCompositeStructureDiagram', 'UMLProfileDiagram',
'UMLTimingDiagram', 'UMLInteractionOverviewDiagram', 'UMLInformationFlowDiagram',
// Flowchart / DFD
'FCFlowchartDiagram', 'DFDDiagram',
// BPMN / C4
'BPMNDiagram', 'C4Diagram',
// SysML
'SysMLRequirementDiagram', 'SysMLBlockDefinitionDiagram',
'SysMLInternalBlockDiagram', 'SysMLParametricDiagram',
// Wireframe / MindMap
'WFWireframeDiagram', 'MMMindmapDiagram',
// Cloud
'AWSDiagram', 'AzureDiagram', 'GCPDiagram'
]
const ALLOWED_NODE_TYPES = [
// Class diagram
'UMLClass', 'UMLInterface', 'UMLSignal', 'UMLDataType', 'UMLPrimitiveType',
'UMLEnumeration', 'UMLPackage', 'UMLModel', 'UMLSubsystem', 'UMLNaryAssociationNode',
// Use case diagram
'UMLActor', 'UMLUseCase', 'UMLUseCaseSubject',
// Activity diagram
'UMLAction', 'UMLObjectNode', 'UMLCentralBufferNode', 'UMLDataStoreNode',
'UMLInitialNode',
'UMLActivityFinalNode', 'UMLFlowFinalNode', 'UMLForkNode', 'UMLJoinNode',
'UMLMergeNode', 'UMLDecisionNode', 'UMLActivityPartition', 'UMLExpansionRegion',
'UMLActivityParameterNode', 'UMLInputPin', 'UMLOutputPin',
'UMLInputExpansionNode', 'UMLOutputExpansionNode', 'UMLInterruptibleActivityRegion',
'UMLStructuredActivityNode', 'UMLActivityEdgeConnector',
// State machine diagram
'UMLState', 'UMLSubmachineState', 'UMLPseudostate', 'UMLFinalState',
'UMLConnectionPointReference',
// Composite structure diagram
'UMLPort', 'UMLPart', 'UMLCollaboration', 'UMLCollaborationUse', 'UMLAssociationClass',
// Information flow diagram
'UMLInformationItem',
// Profile diagram
'UMLProfile', 'UMLStereotype', 'UMLMetaClass',
// Timing diagram
'UMLTimingState', 'UMLDurationConstraint', 'UMLTimeTick', 'UMLTimeConstraint',
// Interaction overview diagram
'UMLInteractionUseInOverview', 'UMLInteractionInOverview',
// Sequence diagram additional
'UMLEndpoint', 'UMLGate', 'UMLContinuation',
// Component diagram
'UMLComponent', 'UMLArtifact',
// Deployment diagram
'UMLNode', 'UMLArtifactInstance', 'UMLComponentInstance', 'UMLNodeInstance',
// Object diagram
'UMLObject',
// Communication diagram
'UMLLifeline',
// Flowchart
'FCProcess', 'FCTerminator', 'FCDecision', 'FCDelay', 'FCPredefinedProcess',
'FCAlternateProcess', 'FCData', 'FCDocument', 'FCMultiDocument', 'FCPreparation',
'FCDisplay', 'FCManualInput', 'FCManualOperation', 'FCCard', 'FCPunchedTape',
'FCConnector', 'FCOffPageConnector', 'FCOr', 'FCSummingJunction', 'FCCollate',
'FCSort', 'FCMerge', 'FCExtract', 'FCStoredData', 'FCDatabase',
'FCDirectAccessStorage', 'FCInternalStorage',
// DFD
'DFDExternalEntity', 'DFDProcess', 'DFDDataStore',
// BPMN
'BPMNParticipant', 'BPMNLane',
'BPMNCallActivity', 'BPMNTask', 'BPMNSendTask', 'BPMNReceiveTask', 'BPMNServiceTask',
'BPMNUserTask', 'BPMNManualTask', 'BPMNBusinessRuleTask', 'BPMNScriptTask',
'BPMNSubProcess', 'BPMNAdHocSubProcess', 'BPMNTransaction',
'BPMNChoreographyTask', 'BPMNSubChoreography',
'BPMNStartEvent', 'BPMNIntermediateThrowEvent', 'BPMNIntermediateCatchEvent',
'BPMNBoundaryEvent', 'BPMNEndEvent',
'BPMNExclusiveGateway', 'BPMNInclusiveGateway', 'BPMNComplexGateway',
'BPMNParallelGateway', 'BPMNEventBasedGateway',
'BPMNDataObject', 'BPMNDataStore', 'BPMNDataInput', 'BPMNDataOutput', 'BPMNMessage',
'BPMNConversation', 'BPMNSubConversation', 'BPMNCallConversation',
'BPMNTextAnnotation', 'BPMNGroup',
// C4
'C4Person', 'C4SoftwareSystem', 'C4Container', 'C4ContainerDatabase',
'C4ContainerWebApp', 'C4ContainerDesktopApp', 'C4ContainerMobileApp', 'C4Component', 'C4Element',
// SysML
'SysMLStakeholder', 'SysMLView', 'SysMLViewpoint', 'SysMLRequirement',
'SysMLBlock', 'SysMLValueType', 'SysMLInterfaceBlock', 'SysMLConstraintBlock',
'SysMLPart', 'SysMLReference', 'SysMLValue', 'SysMLPort', 'SysMLConstraintProperty', 'SysMLConstraintParameter',
// Wireframe
'WFFrame', 'WFMobileFrame', 'WFWebFrame', 'WFDesktopFrame',
'WFButton', 'WFText', 'WFRadio', 'WFCheckbox', 'WFSwitch', 'WFLink',
'WFTabList', 'WFTab', 'WFInput', 'WFDropdown', 'WFPanel', 'WFImage', 'WFSeparator', 'WFAvatar', 'WFSlider',
// MindMap
'MMNode',
// AWS
'AWSElement', 'AWSGroup', 'AWSGenericGroup', 'AWSAvailabilityZone',
'AWSSecurityGroup', 'AWSService', 'AWSResource', 'AWSGeneralResource', 'AWSCallout',
// Azure
'AzureElement', 'AzureGroup', 'AzureService', 'AzureCallout',
// GCP
'GCPElement', 'GCPUser', 'GCPZone', 'GCPProduct', 'GCPService'
]
const ALLOWED_RELATION_TYPES = [
// Class diagram
'UMLAssociation', 'UMLDependency', 'UMLGeneralization', 'UMLInterfaceRealization',
'UMLTemplateBinding', 'UMLContainment', 'UMLRealization',
// Use case diagram
'UMLInclude', 'UMLExtend',
// Activity diagram
'UMLControlFlow', 'UMLObjectFlow', 'UMLExceptionHandler', 'UMLActivityInterrupt',
// State machine diagram
'UMLTransition',
// Composite structure / Information flow
'UMLRoleBinding', 'UMLInformationFlow',
// Profile
'UMLExtension',
// Timing
'UMLTimeSegment',
// Component diagram
'UMLComponentRealization',
// Deployment diagram
'UMLDeployment', 'UMLCommunicationPath',
// Object diagram
'UMLLink',
// Communication diagram
'UMLConnector',
// Flowchart
'FCFlow',
// DFD
'DFDDataFlow',
// BPMN
'BPMNSequenceFlow', 'BPMNMessageFlow', 'BPMNAssociation',
'BPMNDataAssociation', 'BPMNMessageLink', 'BPMNConversationLink',
// C4
'C4Relationship',
// SysML
'SysMLConform', 'SysMLExpose', 'SysMLCopy', 'SysMLDeriveReqt',
'SysMLVerify', 'SysMLSatisfy', 'SysMLRefine', 'SysMLConnector',
// MindMap
'MMEdge',
// AWS
'AWSArrow',
// Azure
'AzureConnector',
// GCP
'GCPPath'
]
const ALLOWED_CHILD_TYPES = [
'UMLAttribute', 'UMLOperation', 'UMLParameter', 'UMLEnumerationLiteral',
'UMLPort', 'UMLReception', 'UMLExtensionPoint', 'UMLSlot',
'UMLTemplateParameter', 'UMLRegion', 'UMLConstraint',
'UMLInteractionOperand',
'SysMLProperty', 'SysMLOperation', 'SysMLFlowProperty',
'UMLInputPin', 'UMLOutputPin',
// BPMN Event Definitions
'BPMNCompensateEventDefinition', 'BPMNCancelEventDefinition',
'BPMNErrorEventDefinition', 'BPMNLinkEventDefinition',
'BPMNSignalEventDefinition', 'BPMNTimerEventDefinition',
'BPMNEscalationEventDefinition', 'BPMNMessageEventDefinition',
'BPMNTerminateEventDefinition', 'BPMNConditionalEventDefinition'
]
const CHILD_TYPE_DEFAULT_FIELDS = {
'UMLAttribute': 'attributes',
'UMLOperation': 'operations',
'UMLParameter': 'parameters',
'UMLEnumerationLiteral': 'literals',
'UMLPort': 'ports',
'UMLReception': 'receptions',
'UMLExtensionPoint': 'extensionPoints',
'UMLSlot': 'slots',
'UMLTemplateParameter': 'templateParameters',
'UMLRegion': 'regions',
'UMLConstraint': 'constraints',
'UMLInteractionOperand': 'operands',
'SysMLProperty': 'properties',
'SysMLOperation': 'operations',
'SysMLFlowProperty': 'flowProperties',
'UMLInputPin': 'inputs',
'UMLOutputPin': 'outputs',
'BPMNCompensateEventDefinition': 'eventDefinitions',
'BPMNCancelEventDefinition': 'eventDefinitions',
'BPMNErrorEventDefinition': 'eventDefinitions',
'BPMNLinkEventDefinition': 'eventDefinitions',
'BPMNSignalEventDefinition': 'eventDefinitions',
'BPMNTimerEventDefinition': 'eventDefinitions',
'BPMNEscalationEventDefinition': 'eventDefinitions',
'BPMNMessageEventDefinition': 'eventDefinitions',
'BPMNTerminateEventDefinition': 'eventDefinitions',
'BPMNConditionalEventDefinition': 'eventDefinitions'
}
const VALID_PSEUDOSTATE_KINDS = [
'initial', 'deepHistory', 'shallowHistory', 'join', 'fork',
'junction', 'choice', 'entryPoint', 'exitPoint'
]
const STYLE_ALLOWED_FIELDS = [
'fillColor', 'lineColor', 'fontColor', 'fontFace', 'fontSize',
'fontStyle', 'lineStyle', 'showShadow', 'autoResize', 'stereotypeDisplay',
'suppressAttributes', 'suppressOperations', 'suppressReceptions',
'suppressProperties'
]
const GENERIC_DIAGRAM_CREATE_FIELDS = ['type', 'name', 'parentId']
const GENERIC_ELEMENT_CREATE_FIELDS = ['type', 'name', 'x1', 'y1', 'x2', 'y2', 'pseudostateKind', 'attachToViewId']
const GENERIC_RELATION_CREATE_FIELDS = ['type', 'sourceId', 'targetId', 'name']
// Types whose factory functions expect the diagram itself as parent (not diagram._parent).
// These factory functions internally resolve the actual parent from the diagram.
const DIAGRAM_AS_PARENT_TYPES = ['SysMLConstraintParameter']
const GENERIC_CHILD_CREATE_FIELDS = ['type', 'name', 'field']
const LAYOUT_ALLOWED_FIELDS = ['direction', 'separations', 'edgeLineStyle']
const IMPORT_ALLOWED_FIELDS = ['path', 'parentId']
const VALID_LAYOUT_DIRECTIONS = ['TB', 'BT', 'LR', 'RL']
// ============================================================
// Validation Helpers
// ============================================================
/**
* Check for unknown fields in body. Returns error string or null.
*/
function checkUnknownFields(body, allowedFields) {
const unknown = Object.keys(body).filter(function (k) {
return allowedFields.indexOf(k) === -1
})
if (unknown.length > 0) {
return 'Unknown field(s): ' + unknown.join(', ') + '. Allowed fields: ' + allowedFields.join(', ')
}
return null
}
/**
* Validate field type. Returns error string or null.
*/
function checkFieldType(body, field, expectedType) {
if (body[field] === undefined) {
return null
}
const val = body[field]
if (expectedType === 'string' && typeof val !== 'string') {
return 'Field "' + field + '" must be a string, got ' + typeof val
}
if (expectedType === 'boolean' && typeof val !== 'boolean') {
return 'Field "' + field + '" must be a boolean, got ' + typeof val
}
if (expectedType === 'number' && typeof val !== 'number') {
return 'Field "' + field + '" must be a number, got ' + typeof val
}
if (expectedType === 'object' && (typeof val !== 'object' || val === null || Array.isArray(val))) {
return 'Field "' + field + '" must be an object'
}
if (expectedType === 'string|null' && val !== null && typeof val !== 'string') {
return 'Field "' + field + '" must be a string or null, got ' + typeof val
}
return null
}
/**
* Validate column type value against ALLOWED_COLUMN_TYPES.
*/
function checkColumnType(value) {
if (value === undefined) {
return null
}
const upper = String(value).toUpperCase()
if (ALLOWED_COLUMN_TYPES.indexOf(upper) === -1) {
return 'Invalid column type "' + value + '". Allowed types: ' + ALLOWED_COLUMN_TYPES.join(', ')
}
return null
}
/**
* Validate tag kind value.
*/
function checkTagKind(value) {
if (value === undefined) {
return null
}
if (VALID_TAG_KINDS.indexOf(value) === -1) {
const labels = VALID_TAG_KINDS.map(function (k) { return k + '=' + TAG_KIND_LABELS[k] })
return 'Invalid tag kind ' + value + '. Allowed values: ' + labels.join(', ')
}
return null
}
/**
* Validate tag value type (string, number, or boolean).
*/
function checkTagValue(value) {
if (value === undefined) {
return null
}
if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {
return 'Field "value" must be a string, number, or boolean, got ' + typeof value
}
return null
}
/**
* Validate non-empty string.
*/
function checkNonEmptyString(body, field) {
if (body[field] === undefined) {
return null
}
if (typeof body[field] !== 'string' || body[field].trim() === '') {
return 'Field "' + field + '" must be a non-empty string'
}
return null
}
/**
* Run multiple validations. Returns first error or null.
*/
function validate(checks) {
for (let i = 0; i < checks.length; i++) {
if (checks[i]) {
return checks[i]
}
}
return null
}
/**
* Build a 400 error response with request context.
*/
function validationError(error, requestInfo, body) {
const result = { success: false, error: error, request: requestInfo }
if (body && Object.keys(body).length > 0) {
result.request = Object.assign({}, requestInfo, { body: body })
}
return result
}
// ============================================================
// Serialization
// ============================================================
function serializeElement(elem) {
if (!elem) {
return null
}
const result = {
_id: elem._id,
_type: elem.constructor.name,
name: elem.name || ''
}
if (elem.documentation) {
result.documentation = elem.documentation
}
return result
}
function serializeEntity(entity) {
const result = serializeElement(entity)
if (!result) {
return null
}
result.columns = (entity.columns || []).map(function (col) {
return serializeColumn(col)
})
result.tags = (entity.tags || []).filter(function (tag) {
return !isSequenceTag(tag) && !isIndexTag(tag)
}).map(function (tag) {
return serializeTag(tag)
})
if (entity._parent) {
result._parentId = entity._parent._id
}
return result
}
function serializeColumn(col) {
if (!col) {
return null
}
const result = {
_id: col._id,
_type: col.constructor.name,
name: col.name || '',
type: col.type || '',
length: col.length || '',
primaryKey: col.primaryKey || false,
foreignKey: col.foreignKey || false,
nullable: col.nullable || false,
unique: col.unique || false
}
if (col.documentation) {
result.documentation = col.documentation
}
if (col.referenceTo) {
result.referenceTo = col.referenceTo._id
}
if (col._parent) {
result._parentId = col._parent._id
}
result.tags = (col.tags || []).map(function (tag) {
return serializeTag(tag)
})
return result
}
function serializeTag(tag) {
if (!tag) {
return null
}
const result = {
_id: tag._id,
_type: tag.constructor.name,
name: tag.name || '',
kind: tag.kind,
value: tag.value
}
if (tag._parent) {
result._parentId = tag._parent._id
}
return result
}
function serializeSequence(tag) {
if (!tag) {
return null
}
return {
_id: tag._id,
_type: 'Sequence',
name: sequenceNameFromTag(tag),
value: tag.value,
_parentId: tag._parent ? tag._parent._id : null
}
}
function serializeIndex(tag) {
if (!tag) {
return null
}
return {
_id: tag._id,
_type: 'Index',
name: indexNameFromTag(tag),
definition: tag.value,
_parentId: tag._parent ? tag._parent._id : null
}
}
function serializeRelationship(rel) {
if (!rel) {
return null
}
const result = {
_id: rel._id,
_type: rel.constructor.name,
name: rel.name || '',
identifying: rel.identifying || false
}
if (rel.end1) {
result.end1 = {
name: rel.end1.name || '',
cardinality: rel.end1.cardinality || '',
reference: rel.end1.reference ? rel.end1.reference._id : null
}
}
if (rel.end2) {
result.end2 = {
name: rel.end2.name || '',
cardinality: rel.end2.cardinality || '',
reference: rel.end2.reference ? rel.end2.reference._id : null
}
}
if (rel._parent) {
result._parentId = rel._parent._id
}
return result
}
function serializeDiagram(diagram) {
if (!diagram) {
return null
}
const result = serializeElement(diagram)
const entityIds = []
if (diagram.ownedViews) {
diagram.ownedViews.forEach(function (view) {
if (view.model && view.model instanceof type.ERDEntity) {
entityIds.push(view.model._id)
}
})
}
result.entityIds = entityIds
if (diagram._parent) {
result._parentId = diagram._parent._id
}
return result
}
function serializeGenericDiagram(diagram) {
if (!diagram) {
return null
}
return {
_id: diagram._id,
_type: diagram.constructor.name,
name: diagram.name || '',
_parentId: diagram._parent ? diagram._parent._id : null
}
}
function serializeNoteView(view) {
if (!view) {
return null
}
return {
_id: view._id,
_type: view.constructor.name,
text: view.text || '',
left: view.left !== undefined ? view.left : 0,
top: view.top !== undefined ? view.top : 0,
width: view.width !== undefined ? view.width : 0,
height: view.height !== undefined ? view.height : 0
}
}
function serializeNoteLinkView(view) {
if (!view) {
return null
}
return {
_id: view._id,
_type: view.constructor.name,
noteId: view.tail ? view.tail._id : null,
targetId: view.head ? view.head._id : null
}
}
function serializeFreeLineView(view) {
if (!view) {
return null
}
const result = {
_id: view._id,
_type: view.constructor.name
}
// Points is a StarUML Points collection: view.points.points is the internal array
if (view.points) {
let pts = null
if (typeof view.points.count === 'function' && view.points.count() >= 2) {
const p1 = view.points.getPoint(0)
const p2 = view.points.getPoint(view.points.count() - 1)
pts = { p1: p1, p2: p2 }
} else if (view.points.points && view.points.points.length >= 2) {
pts = { p1: view.points.points[0], p2: view.points.points[view.points.points.length - 1] }
}
if (pts) {
result.x1 = pts.p1.x
result.y1 = pts.p1.y
result.x2 = pts.p2.x
result.y2 = pts.p2.y
}
}
return result
}
function serializeViewInfo(view) {
if (!view) {
return null
}
const result = {
_id: view._id,
_type: view.constructor.name
}
if (view.model) {
result.modelId = view.model._id
}
if (view.left !== undefined) {
result.left = view.left
}
if (view.top !== undefined) {
result.top = view.top
}
if (view.width !== undefined) {
result.width = view.width
}
if (view.height !== undefined) {
result.height = view.height
}
return result
}
// ============================================================
// Helpers
// ============================================================
function findById(id) {
return app.repository.get(id) || null
}
function isSequenceTag(tag) {
return tag && tag.name && tag.name.indexOf(SEQUENCE_PREFIX) === 0
}
function isIndexTag(tag) {
return tag && tag.name && tag.name.indexOf(INDEX_PREFIX) === 0
}
function sequenceNameFromTag(tag) {
return tag.name.substring(SEQUENCE_PREFIX.length)
}
function indexNameFromTag(tag) {
return tag.name.substring(INDEX_PREFIX.length)
}
/**
* Find columns in other entities that reference the given column via referenceTo.
*/
function findColumnsReferencingColumn(columnId) {
const allColumns = app.repository.select('@ERDColumn')
const result = []
for (let i = 0; i < allColumns.length; i++) {
const col = allColumns[i]
if (col.referenceTo && col.referenceTo._id === columnId) {
result.push({
columnId: col._id,
columnName: col.name,
entityId: col._parent ? col._parent._id : null,
entityName: col._parent ? col._parent.name : ''
})
}
}
return result
}
/**
* Find columns in other entities that reference any column of the given entity via referenceTo.
*/
function findColumnsReferencingEntity(entityId) {
const entity = findById(entityId)
if (!entity) {
return []
}
const entityColumnIds = {}
const entityColumnNames = {}
const columns = entity.columns || []
for (let i = 0; i < columns.length; i++) {
entityColumnIds[columns[i]._id] = true
entityColumnNames[columns[i]._id] = columns[i].name
}
const allColumns = app.repository.select('@ERDColumn')
const result = []
for (let j = 0; j < allColumns.length; j++) {
const col = allColumns[j]
if (col.referenceTo && entityColumnIds[col.referenceTo._id]) {
if (col._parent && col._parent._id === entityId) {
continue
}
result.push({
columnId: col._id,
columnName: col.name,
entityId: col._parent ? col._parent._id : null,
entityName: col._parent ? col._parent.name : '',
referencedColumnId: col.referenceTo._id,
referencedColumnName: entityColumnNames[col.referenceTo._id] || ''
})
}
}
return result
}
/**
* Find relationships that reference the given entity via end1 or end2.
*/
function findRelationshipsReferencingEntity(entityId) {
const allRels = app.repository.select('@ERDRelationship')
const result = []
for (let i = 0; i < allRels.length; i++) {
const rel = allRels[i]
const ends = []
if (rel.end1 && rel.end1.reference && rel.end1.reference._id === entityId) {
ends.push('end1')
}
if (rel.end2 && rel.end2.reference && rel.end2.reference._id === entityId) {
ends.push('end2')
}
if (ends.length > 0) {
result.push({
relationshipId: rel._id,
relationshipName: rel.name || rel._id,
ends: ends
})
}
}
return result
}
// ============================================================
// Route Handlers
// ============================================================
const ENTITY_ALLOWED_FIELDS = ['parentId', 'name', 'documentation', 'diagramId', 'x1', 'y1', 'x2', 'y2']
const ENTITY_UPDATE_FIELDS = ['name', 'documentation']
const COLUMN_ALLOWED_FIELDS = ['name', 'type', 'length', 'primaryKey', 'foreignKey', 'nullable', 'unique', 'documentation', 'referenceToId']
const TAG_ALLOWED_FIELDS = ['name', 'kind', 'value']
const RELATIONSHIP_ALLOWED_FIELDS = ['parentId', 'name', 'identifying', 'end1', 'end2', 'diagramId']
const RELATIONSHIP_UPDATE_FIELDS = ['name', 'identifying', 'end1', 'end2']
const RELATIONSHIP_END_CREATE_FIELDS = ['reference', 'name', 'cardinality']
const RELATIONSHIP_END_FIELDS = ['name', 'cardinality', 'reference']
const DATA_MODEL_ALLOWED_FIELDS = ['name']
const DATA_MODEL_UPDATE_FIELDS = ['name']
const DIAGRAM_ALLOWED_FIELDS = ['parentId', 'name']
const DIAGRAM_UPDATE_FIELDS = ['name']
const PROJECT_SAVE_ALLOWED_FIELDS = ['path']
const PROJECT_OPEN_ALLOWED_FIELDS = ['path']
// --- Generic / Cross-diagram Constants ---
const NOTE_ALLOWED_FIELDS = ['text', 'x1', 'y1', 'x2', 'y2']
const NOTE_UPDATE_FIELDS = ['text']
const NOTE_LINK_ALLOWED_FIELDS = ['noteId', 'targetId']
const FREE_LINE_ALLOWED_FIELDS = ['x1', 'y1', 'x2', 'y2']
const VIEW_UPDATE_FIELDS = ['left', 'top', 'width', 'height']
const GENERIC_ELEMENT_UPDATE_FIELDS = ['name', 'documentation']
const EXPORT_ALLOWED_FIELDS = ['path', 'format']
const VALID_EXPORT_FORMATS = ['png', 'jpeg', 'svg', 'pdf']
// --- Shape (view-only) Constants ---
const ALLOWED_SHAPE_TYPES = ['Text', 'TextBox', 'Rect', 'RoundRect', 'Ellipse', 'Hyperlink', 'Image', 'UMLFrame']
const SHAPE_CREATE_FIELDS = ['type', 'text', 'url', 'imageFile', 'x1', 'y1', 'x2', 'y2']
const SHAPE_UPDATE_FIELDS = ['text', 'url', 'imageFile']
const SHAPE_VIEW_TYPE_MAP = {
'UMLTextView': 'Text',
'UMLTextBoxView': 'TextBox',
'RectangleView': 'Rect',
'RoundRectView': 'RoundRect',
'EllipseView': 'Ellipse',
'HyperlinkView': 'Hyperlink',
'ImageView': 'Image',
'UMLFrameView': 'UMLFrame'
}
const SHAPE_VIEW_TYPES = Object.keys(SHAPE_VIEW_TYPE_MAP)
// --- Diagrams ---
function getDiagrams(reqInfo) {
const diagrams = app.repository.select('@ERDDiagram')
return {
success: true,
message: 'Retrieved ' + diagrams.length + ' diagram(s)',
request: reqInfo,
data: diagrams.map(function (d) { return serializeDiagram(d) })
}
}
function getDiagram(id, reqInfo) {
const diagram = findById(id)
if (!diagram || !(diagram instanceof type.ERDDiagram)) {
return { success: false, error: 'Diagram not found: ' + id, request: reqInfo }
}
return {
success: true,
message: 'Retrieved diagram "' + diagram.name + '"',
request: reqInfo,
data: serializeDiagram(diagram)
}
}
function createDiagram(body, reqInfo) {
const err = validate([
checkUnknownFields(body, DIAGRAM_ALLOWED_FIELDS),
checkFieldType(body, 'parentId', 'string'),
checkFieldType(body, 'name', 'string')
])
if (err) {
return validationError(err, reqInfo, body)
}
if (!body.parentId) {
return validationError('Field "parentId" is required', reqInfo, body)
}
if (body.name !== undefined) {
const nameErr = checkNonEmptyString(body, 'name')
if (nameErr) {
return validationError(nameErr, reqInfo, body)
}
}
const parent = findById(body.parentId)
if (!parent || !(parent instanceof type.ERDDataModel)) {
return validationError('parentId must refer to an ERDDataModel. Not found or wrong type: ' + body.parentId, reqInfo, body)
}
const diagram = app.factory.createDiagram({
id: 'ERDDiagram',
parent: parent,
diagramInitializer: function (d) {
d.name = body.name || 'ERDDiagram1'
}
})
return {
success: true,
message: 'Created diagram "' + diagram.name + '"',
request: Object.assign({}, reqInfo, { body: body }),
data: serializeDiagram(diagram)
}
}
function updateDiagram(id, body, reqInfo) {
const err = validate([
checkUnknownFields(body, DIAGRAM_UPDATE_FIELDS),
checkFieldType(body, 'name', 'string')
])
if (err) {
return validationError(err, reqInfo, body)
}
if (Object.keys(body).length === 0) {
return validationError('At least one field must be provided. Allowed fields: ' + DIAGRAM_UPDATE_FIELDS.join(', '), reqInfo, body)
}
if (body.name !== undefined) {
const nameErr = checkNonEmptyString(body, 'name')
if (nameErr) {
return validationError(nameErr, reqInfo, body)
}
}
const diagram = findById(id)
if (!diagram || !(diagram instanceof type.ERDDiagram)) {
return { success: false, error: 'Diagram not found: ' + id, request: Object.assign({}, reqInfo, { body: body }) }
}
const updated = []
if (body.name !== undefined) {
app.engine.setProperty(diagram, 'name', body.name)
updated.push('name')
}
return {
success: true,
message: 'Updated diagram "' + diagram.name + '" (fields: ' + updated.join(', ') + ')',
request: Object.assign({}, reqInfo, { body: body }),
data: serializeDiagram(diagram)
}
}
function deleteDiagram(id, reqInfo) {
const diagram = findById(id)
if (!diagram || !(diagram instanceof type.ERDDiagram)) {
return { success: false, error: 'Diagram not found: ' + id, request: reqInfo }
}
const name = diagram.name
app.engine.deleteElements([diagram], [])
return {
success: true,
message: 'Deleted diagram "' + name + '"',
request: reqInfo,
data: { deleted: id, name: name }
}
}
// --- Data Models ---
function getDataModels(reqInfo) {
const models = app.repository.select('@ERDDataModel')
return {
success: true,
message: 'Retrieved ' + models.length + ' data model(s)',
request: reqInfo,
data: models.map(function (m) { return serializeElement(m) })
}
}
function getDataModel(id, reqInfo) {
const dm = findById(id)
if (!dm || !(dm instanceof type.ERDDataModel)) {
return { success: false, error: 'Data model not found: ' + id, request: reqInfo }
}
return {
success: true,
message: 'Retrieved data model "' + dm.name + '"',
request: reqInfo,
data: serializeElement(dm)
}
}
function createDataModel(body, reqInfo) {
const err = validate([
checkUnknownFields(body, DATA_MODEL_ALLOWED_FIELDS),
checkFieldType(body, 'name', 'string')
])
if (err) {
return validationError(err, reqInfo, body)
}
if (body.name !== undefined) {
const nameErr = checkNonEmptyString(body, 'name')
if (nameErr) {
return validationError(nameErr, reqInfo, body)
}
}
const project = app.repository.select('@Project')[0]
if (!project) {
return validationError('No project found. Open a project first.', reqInfo, body)
}