forked from Luligu/matterbridge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_model.mjs
More file actions
2058 lines (1606 loc) · 62.8 KB
/
Copy pathdata_model.mjs
File metadata and controls
2058 lines (1606 loc) · 62.8 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
/**
* Data model script.
*
* This script will fetch from the connectedhomeip GitHub repository the data model files and convert them to JSON.
*
* It supports environment variables to customize the version and output paths.
*
* MATTER_DATA_MODEL_VERSION - The default version is 1.4.2.
*/
const MATTER_DATA_MODEL_VERSION = process.env.MATTER_DATA_MODEL_VERSION || '1.4.2';
const SRC_PATH = `https://raw.githubusercontent.com/project-chip/connectedhomeip/master/data_model/${MATTER_DATA_MODEL_VERSION}/`;
const DATA_MODEL_PATHS = {
clusters: `${SRC_PATH}clusters/`,
clustersIds: `${SRC_PATH}clusters/cluster_ids.json`,
deviceTypes: `${SRC_PATH}device_types/`,
deviceTypesIds: `${SRC_PATH}device_types/device_type_ids.json`,
namespaces: `${SRC_PATH}namespaces/`,
};
const DST_PATH = `chip/${MATTER_DATA_MODEL_VERSION}/`;
const OUTPUT_NAMESPACES = 'namespaces.json';
const OUTPUT_DEVICE_TYPES = 'deviceTypes.json';
const OUTPUT_CLUSTERS = 'clusters.json';
const GITHUB_API_BASE = 'https://api.github.com/repos/project-chip/connectedhomeip/contents';
const DEVICE_TYPES_DIRECTORY_API = `${GITHUB_API_BASE}/data_model/${MATTER_DATA_MODEL_VERSION}/device_types?ref=master`;
const CLUSTERS_DIRECTORY_API = `${GITHUB_API_BASE}/data_model/${MATTER_DATA_MODEL_VERSION}/clusters?ref=master`;
const GITHUB_API_HEADERS = {
'User-Agent': 'matterbridge-data-model-script',
Accept: 'application/vnd.github.v3+json',
};
const sanitizeKey = (value) => value.replace(/[\s/]+/g, '');
const normalizeDisplayName = (value) => (typeof value === 'string' ? value.replace(/\s*\/\s*/g, '') : value);
const cloneDeep = (value) => {
if (value === undefined) {
return undefined;
}
return typeof structuredClone === 'function' ? structuredClone(value) : JSON.parse(JSON.stringify(value));
};
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { request } from 'node:https';
const fetchRemoteText = async (url, { description, headers = {}, maxRedirects = 5 } = {}) => {
const label = description || url;
const download = (target, redirectCount = 0) =>
new Promise((resolve, reject) => {
const req = request(target, { headers }, (res) => {
const { statusCode = 0, headers: responseHeaders } = res;
if (statusCode >= 300 && statusCode < 400 && responseHeaders.location) {
if (redirectCount >= maxRedirects) {
reject(new Error(`Too many redirects while fetching ${label}`));
return;
}
const redirectUrl = new URL(responseHeaders.location, target).toString();
resolve(download(redirectUrl, redirectCount + 1));
return;
}
if (statusCode < 200 || statusCode >= 300) {
reject(new Error(`Failed to download ${label}: ${statusCode}`));
return;
}
const chunks = [];
res.on('data', (chunk) => chunks.push(chunk));
res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
});
req.on('error', (error) => {
reject(new Error(`Request error while fetching ${label}: ${error.message}`));
});
req.end();
});
return download(url);
};
const fetchJson = async (url, { description, headers, maxRedirects } = {}) => {
const text = await fetchRemoteText(url, { description, headers, maxRedirects });
try {
return JSON.parse(text);
} catch (error) {
throw new Error(`Unable to parse JSON from ${description || url}: ${error.message}`);
}
};
/* eslint-disable no-console */
const decodeEntities = (value) =>
value
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'");
const parseHexId = (rawValue, context) => {
const value = rawValue.trim();
const match = value.match(/^0x([0-9a-fA-F]+)$/);
if (!match) {
throw new Error(`Invalid hex id "${rawValue}" encountered while parsing ${context}.`);
}
const digits = match[1];
return Number.parseInt(digits, 16);
};
const parseAttributes = (fragment) => {
const attributes = {};
const attrRegex = /([A-Za-z_:][A-Za-z0-9_.:-]*)\s*=\s*"([^"]*)"/g;
let match;
while ((match = attrRegex.exec(fragment)) !== null) {
const [, key, rawValue] = match;
attributes[key] = decodeEntities(rawValue.trim());
}
return attributes;
};
const parseNumericValue = (rawValue) => {
if (rawValue === undefined) {
return undefined;
}
const value = rawValue.trim();
if (/^[-+]?0x[0-9a-f]+$/i.test(value)) {
return Number.parseInt(value, 16);
}
if (/^[-+]?\d+$/.test(value)) {
const parsed = Number.parseInt(value, 10);
return Number.isNaN(parsed) ? value : parsed;
}
return value;
};
const parseScalarValue = (rawValue) => {
if (rawValue === undefined) {
return undefined;
}
const trimmed = rawValue.trim();
if (!trimmed) {
return '';
}
const normalized = trimmed.toLowerCase();
if (normalized === 'true') {
return true;
}
if (normalized === 'false') {
return false;
}
const numeric = parseNumericValue(trimmed);
if (typeof numeric === 'number') {
return numeric;
}
return trimmed;
};
const toCamelCase = (value) => value.replace(/[-_:](\w)/g, (match, letter) => letter.toUpperCase());
const prefixDirectiveKey = (prefix, key) => {
const camelKey = toCamelCase(key);
return `${prefix}${camelKey.charAt(0).toUpperCase()}${camelKey.slice(1)}`;
};
const CONFORMANCE_TAGS = [
['mandatoryConform', 'mandatory'],
['optionalConform', 'optional'],
['disallowConform', 'disallow'],
['provisionalConform', 'provisional'],
['deprecateConform', 'deprecate'],
['otherwiseConform', 'otherwise'],
];
const parseConformanceEntries = (fragment) => {
if (!fragment) {
return [];
}
const entries = [];
for (const [tag, status] of CONFORMANCE_TAGS) {
const regex = new RegExp(`<${tag}\\b[^>]*>`, 'gi');
let match;
while ((match = regex.exec(fragment)) !== null) {
const attributes = parseAttributes(match[0]);
const entry = { status };
if (Object.keys(attributes).length > 0) {
entry.attributes = attributes;
}
entries.push(entry);
}
}
return entries;
};
const extractConditions = (fragment) => {
if (!fragment) {
return [];
}
const conditions = [];
const regex = /<condition\b[^>]*>/gi;
let match;
while ((match = regex.exec(fragment)) !== null) {
const attributes = parseAttributes(match[0]);
const { name, summary = '', ...rest } = attributes;
if (!name) {
continue;
}
const condition = { name };
if (summary) {
condition.summary = summary;
}
if (Object.keys(rest).length > 0) {
condition.attributes = rest;
}
conditions.push(condition);
}
return conditions;
};
const extractFeatureRefs = (fragment) => {
if (!fragment) {
return [];
}
const names = new Set();
const regex = /<feature\b[^>]*>/gi;
let match;
while ((match = regex.exec(fragment)) !== null) {
const attributes = parseAttributes(match[0]);
const { name } = attributes;
if (name) {
names.add(name);
}
}
return [...names];
};
const extractDirectiveList = (fragment, tagName) => {
if (!fragment) {
return [];
}
const regex = new RegExp(`<${tagName}\\b[^>]*>`, 'gi');
const directives = [];
let match;
while ((match = regex.exec(fragment)) !== null) {
const attributes = parseAttributes(match[0]);
if (Object.keys(attributes).length > 0) {
directives.push(attributes);
} else {
directives.push({});
}
}
return directives;
};
const extractAccessDirectives = (fragment) => extractDirectiveList(fragment, 'access');
const extractQualityDirectives = (fragment) => extractDirectiveList(fragment, 'quality');
const extractEntryDirectives = (fragment) => {
if (!fragment) {
return [];
}
const regex = /<entry\b[^>]*>/gi;
const entries = [];
let match;
while ((match = regex.exec(fragment)) !== null) {
const attributes = parseAttributes(match[0]);
if (Object.keys(attributes).length > 0) {
entries.push(attributes);
} else {
entries.push({});
}
}
return entries;
};
const extractConstraintSnippets = (fragment) => {
if (!fragment) {
return [];
}
const regex = /<constraint\b[^>]*>([\s\S]*?)<\/constraint>/gi;
const constraints = [];
let match;
while ((match = regex.exec(fragment)) !== null) {
const [, body] = match;
const normalized = body.replace(/\s+/g, ' ').trim();
if (normalized) {
constraints.push(normalized);
}
}
return constraints;
};
const removeSegments = (source, segments) => {
if (!segments || segments.length === 0) {
return source;
}
const sorted = [...segments].sort((left, right) => left.start - right.start);
let result = '';
let cursor = 0;
for (const { start, end } of sorted) {
if (cursor < start) {
result += source.slice(cursor, start);
}
cursor = Math.max(cursor, end);
}
if (cursor < source.length) {
result += source.slice(cursor);
}
return result;
};
const parseEnumItems = (enumBody, enumName, clusterName, contextLabel) => {
const items = [];
const itemRegex = /<item\b[^>]*?(?:\/\s*>|>[\s\S]*?<\/item>)/gi;
let match;
while ((match = itemRegex.exec(enumBody)) !== null) {
const fragment = match[0];
const openingMatch = fragment.match(/<item\b[^>]*>/i);
if (!openingMatch) {
throw new Error(`Unable to parse enum item in ${enumName} for cluster ${clusterName} (${contextLabel}).`);
}
const attributes = parseAttributes(openingMatch[0]);
const { name, summary = '', value, ...rest } = attributes;
if (!name) {
throw new Error(`Enum item without a name encountered in ${enumName} for cluster ${clusterName} (${contextLabel}).`);
}
const entry = { name };
if (value !== undefined) {
const parsedValue = parseNumericValue(value);
entry.value = parsedValue !== undefined ? parsedValue : value;
}
if (summary) {
entry.summary = summary;
}
if (Object.keys(rest).length > 0) {
entry.attributes = rest;
}
let body = '';
if (!fragment.trimEnd().endsWith('/>')) {
body = fragment.slice(openingMatch[0].length, fragment.length - '</item>'.length);
}
const conformances = parseConformanceEntries(body);
if (conformances.length > 0) {
entry.conformance = conformances;
}
const conditions = extractConditions(body);
if (conditions.length > 0) {
entry.conditions = conditions;
}
const features = extractFeatureRefs(body);
if (features.length > 0) {
entry.features = features;
}
const access = extractAccessDirectives(body);
if (access.length > 0) {
entry.access = access;
}
const quality = extractQualityDirectives(body);
if (quality.length > 0) {
entry.quality = quality;
}
const constraints = extractConstraintSnippets(body);
if (constraints.length > 0) {
entry.constraints = constraints;
}
items.push(entry);
}
return items;
};
const parseBitmapFields = (bitmapBody, bitmapName, clusterName, contextLabel) => {
const fields = [];
const fieldRegex = /<bitfield\b[^>]*?(?:\/\s*>|>[\s\S]*?<\/bitfield>)/gi;
let match;
while ((match = fieldRegex.exec(bitmapBody)) !== null) {
const fragment = match[0];
const openingMatch = fragment.match(/<bitfield\b[^>]*>/i);
if (!openingMatch) {
throw new Error(`Unable to parse bitfield in ${bitmapName} for cluster ${clusterName} (${contextLabel}).`);
}
const attributes = parseAttributes(openingMatch[0]);
const { name, summary = '', bit, ...rest } = attributes;
if (!name) {
throw new Error(`Bitfield without a name encountered in ${bitmapName} for cluster ${clusterName} (${contextLabel}).`);
}
const entry = { name };
if (bit !== undefined) {
const parsedBit = parseNumericValue(bit);
entry.bit = parsedBit !== undefined ? parsedBit : bit;
}
if (summary) {
entry.summary = summary;
}
if (Object.keys(rest).length > 0) {
entry.attributes = rest;
}
let body = '';
if (!fragment.trimEnd().endsWith('/>')) {
body = fragment.slice(openingMatch[0].length, fragment.length - '</bitfield>'.length);
}
const conformances = parseConformanceEntries(body);
if (conformances.length > 0) {
entry.conformance = conformances;
}
const conditions = extractConditions(body);
if (conditions.length > 0) {
entry.conditions = conditions;
}
const features = extractFeatureRefs(body);
if (features.length > 0) {
entry.features = features;
}
const access = extractAccessDirectives(body);
if (access.length > 0) {
entry.access = access;
}
const quality = extractQualityDirectives(body);
if (quality.length > 0) {
entry.quality = quality;
}
const constraints = extractConstraintSnippets(body);
if (constraints.length > 0) {
entry.constraints = constraints;
}
fields.push(entry);
}
return fields;
};
const parseStructFields = (structBody, structName, clusterName, contextLabel) => {
const fields = [];
const segments = [];
const fieldRegex = /<field\b[^>]*?(?:\/\s*>|>[\s\S]*?<\/field>)/gi;
let match;
while ((match = fieldRegex.exec(structBody)) !== null) {
const fragment = match[0];
const start = match.index;
const end = fieldRegex.lastIndex;
segments.push({ start, end });
const openingMatch = fragment.match(/<field\b[^>]*>/i);
if (!openingMatch) {
throw new Error(`Unable to parse struct field in ${structName} for cluster ${clusterName} (${contextLabel}).`);
}
const attributes = parseAttributes(openingMatch[0]);
const { name, summary = '', id, type, ...rest } = attributes;
if (!name) {
throw new Error(`Struct field without a name encountered in ${structName} for cluster ${clusterName} (${contextLabel}).`);
}
const fieldEntry = { name };
if (type !== undefined) {
fieldEntry.type = type;
}
if (id !== undefined) {
const parsedId = parseNumericValue(id);
fieldEntry.id = parsedId !== undefined ? parsedId : id;
}
if (summary) {
fieldEntry.summary = summary;
}
if (Object.keys(rest).length > 0) {
fieldEntry.attributes = rest;
}
let body = '';
if (!fragment.trimEnd().endsWith('/>')) {
body = fragment.slice(openingMatch[0].length, fragment.length - '</field>'.length);
}
const conformances = parseConformanceEntries(body);
if (conformances.length > 0) {
fieldEntry.conformance = conformances;
}
const conditions = extractConditions(body);
if (conditions.length > 0) {
fieldEntry.conditions = conditions;
}
const features = extractFeatureRefs(body);
if (features.length > 0) {
fieldEntry.features = features;
}
const access = extractAccessDirectives(body);
if (access.length > 0) {
fieldEntry.access = access;
}
const quality = extractQualityDirectives(body);
if (quality.length > 0) {
fieldEntry.quality = quality;
}
const entries = extractEntryDirectives(body);
if (entries.length > 0) {
fieldEntry.entries = entries;
}
const constraints = extractConstraintSnippets(body);
if (constraints.length > 0) {
fieldEntry.constraints = constraints;
}
fields.push(fieldEntry);
}
const remainder = removeSegments(structBody, segments);
return { fields, remainder };
};
const parseDataTypesBlock = (xmlContent, clusterName, contextLabel) => {
const match = xmlContent.match(/<dataTypes\b[^>]*>([\s\S]*?)<\/dataTypes>/i);
if (!match) {
return {};
}
const [, body] = match;
const dataTypes = {};
const regex = /<(enum|bitmap|struct)\b[^>]*>[\s\S]*?<\/\1>/gi;
let typeMatch;
while ((typeMatch = regex.exec(body)) !== null) {
const fullMatch = typeMatch[0];
const rawType = typeMatch[1];
const openingMatch = fullMatch.match(new RegExp(`<${rawType}\\b[^>]*>`, 'i'));
if (!openingMatch) {
throw new Error(`Unable to parse ${rawType} definition for cluster ${clusterName} (${contextLabel}).`);
}
const typeAttributes = parseAttributes(openingMatch[0]);
const { name, summary = '', ...rest } = typeAttributes;
if (!name) {
throw new Error(`Data type (${rawType}) without a name encountered in cluster ${clusterName} (${contextLabel}).`);
}
const typeBody = fullMatch.slice(openingMatch[0].length, fullMatch.length - `</${rawType}>`.length);
const definition = {
type: rawType.toLowerCase(),
name,
};
if (summary) {
definition.summary = summary;
}
if (Object.keys(rest).length > 0) {
definition.attributes = rest;
}
if (definition.type === 'enum') {
const entries = parseEnumItems(typeBody, name, clusterName, contextLabel);
if (entries.length > 0) {
definition.entries = entries;
}
} else if (definition.type === 'bitmap') {
const fields = parseBitmapFields(typeBody, name, clusterName, contextLabel);
if (fields.length > 0) {
definition.fields = fields;
}
} else if (definition.type === 'struct') {
const { fields, remainder } = parseStructFields(typeBody, name, clusterName, contextLabel);
if (fields.length > 0) {
definition.fields = fields;
}
const structConformance = parseConformanceEntries(remainder);
if (structConformance.length > 0) {
definition.conformance = structConformance;
}
const structConditions = extractConditions(remainder);
if (structConditions.length > 0) {
definition.conditions = structConditions;
}
const structFeatures = extractFeatureRefs(remainder);
if (structFeatures.length > 0) {
definition.features = structFeatures;
}
const structAccess = extractAccessDirectives(remainder);
if (structAccess.length > 0) {
definition.access = structAccess;
}
const structQuality = extractQualityDirectives(remainder);
if (structQuality.length > 0) {
definition.quality = structQuality;
}
const structEntries = extractEntryDirectives(remainder);
if (structEntries.length > 0) {
definition.entries = structEntries;
}
const structConstraints = extractConstraintSnippets(remainder);
if (structConstraints.length > 0) {
definition.constraints = structConstraints;
}
}
dataTypes[name] = definition;
}
return dataTypes;
};
const parseAttributesBlock = (xmlContent, clusterName, contextLabel) => {
const match = xmlContent.match(/<attributes\b[^>]*>([\s\S]*?)<\/attributes>/i);
if (!match) {
return {};
}
const [, body] = match;
const attributes = {};
const attributeRegex = /<attribute\b[^>]*?(?:\/\s*>|>[\s\S]*?<\/attribute>)/gi;
let attrMatch;
while ((attrMatch = attributeRegex.exec(body)) !== null) {
const fullMatch = attrMatch[0];
const openingMatch = fullMatch.match(/<attribute\b[^>]*>/i);
if (!openingMatch) {
throw new Error(`Unable to parse attribute definition for cluster ${clusterName} (${contextLabel}).`);
}
const attributeAttributes = parseAttributes(openingMatch[0]);
const { id, name, type, summary = '', ...rest } = attributeAttributes;
if (!name) {
throw new Error(`Attribute without a name encountered in cluster ${clusterName} (${contextLabel}).`);
}
const entry = { name };
if (id !== undefined) {
entry.id = parseHexId(id, `attribute ${name} in cluster ${clusterName}`);
}
if (type !== undefined) {
entry.type = type;
}
if (summary) {
entry.summary = summary;
}
for (const [key, value] of Object.entries(rest)) {
const normalizedKey = toCamelCase(key);
entry[normalizedKey] = parseScalarValue(value);
}
let attributeBody = '';
if (!fullMatch.trimEnd().endsWith('/>')) {
attributeBody = fullMatch.slice(openingMatch[0].length, fullMatch.length - '</attribute>'.length);
}
const directiveSegments = [];
const accessRegex = /<access\b[^>]*?(?:\/\s*>|>[\s\S]*?<\/access>)/gi;
let accessMatch;
while ((accessMatch = accessRegex.exec(attributeBody)) !== null) {
directiveSegments.push({ start: accessMatch.index, end: accessRegex.lastIndex });
const accessAttributes = parseAttributes(accessMatch[0]);
for (const [key, value] of Object.entries(accessAttributes)) {
const propertyKey = prefixDirectiveKey('access', key);
entry[propertyKey] = parseScalarValue(value);
}
}
const qualityRegex = /<quality\b[^>]*?(?:\/\s*>|>[\s\S]*?<\/quality>)/gi;
let qualityMatch;
while ((qualityMatch = qualityRegex.exec(attributeBody)) !== null) {
directiveSegments.push({ start: qualityMatch.index, end: qualityRegex.lastIndex });
const qualityAttributes = parseAttributes(qualityMatch[0]);
for (const [key, value] of Object.entries(qualityAttributes)) {
const propertyKey = prefixDirectiveKey('quality', key);
entry[propertyKey] = parseScalarValue(value);
}
}
const remainder = removeSegments(attributeBody, directiveSegments);
const conformances = parseConformanceEntries(remainder);
if (conformances.length > 0) {
entry.conformance = conformances;
}
const conditions = extractConditions(remainder);
if (conditions.length > 0) {
entry.conditions = conditions;
}
const features = extractFeatureRefs(remainder);
if (features.length > 0) {
entry.features = features;
}
const entries = extractEntryDirectives(remainder);
if (entries.length > 0) {
entry.entries = entries;
}
const constraints = extractConstraintSnippets(remainder);
if (constraints.length > 0) {
entry.constraints = constraints;
}
attributes[name] = entry;
}
return attributes;
};
const parseCommandArguments = (commandBody, commandName, clusterName, contextLabel, directiveSegments) => {
const argumentsMap = {};
const processTag = (tagName) => {
const regex = new RegExp(`<${tagName}\\b[^>]*?(?:\\/\\s*>|>[\\s\\S]*?<\\/${tagName}>)`, 'gi');
regex.lastIndex = 0;
let match;
while ((match = regex.exec(commandBody)) !== null) {
directiveSegments.push({ start: match.index, end: regex.lastIndex });
const fragment = match[0];
const openingMatch = fragment.match(new RegExp(`<${tagName}\\b[^>]*>`, 'i'));
if (!openingMatch) {
throw new Error(`Unable to parse ${tagName} definition for command ${commandName} in cluster ${clusterName} (${contextLabel}).`);
}
const parameterAttributes = parseAttributes(openingMatch[0]);
const { name, id, fieldId, type, summary = '', ...rest } = parameterAttributes;
if (!name) {
throw new Error(`Parameter without a name encountered in command ${commandName} for cluster ${clusterName} (${contextLabel}).`);
}
const parameterEntry = { name };
if (id !== undefined) {
parameterEntry.id = parseNumericValue(id);
}
if (fieldId !== undefined) {
parameterEntry.fieldId = parseNumericValue(fieldId);
}
if (type !== undefined) {
parameterEntry.type = type;
}
if (summary) {
parameterEntry.summary = summary;
}
for (const [key, value] of Object.entries(rest)) {
const normalizedKey = toCamelCase(key);
parameterEntry[normalizedKey] = parseScalarValue(value);
}
let parameterBody = '';
if (!fragment.trimEnd().endsWith('/>')) {
parameterBody = fragment.slice(openingMatch[0].length, fragment.length - `</${tagName}>`.length);
}
const parameterConformance = parseConformanceEntries(parameterBody);
if (parameterConformance.length > 0) {
parameterEntry.conformance = parameterConformance;
}
const parameterConditions = extractConditions(parameterBody);
if (parameterConditions.length > 0) {
parameterEntry.conditions = parameterConditions;
}
const parameterFeatures = extractFeatureRefs(parameterBody);
if (parameterFeatures.length > 0) {
parameterEntry.features = parameterFeatures;
}
const parameterConstraints = extractConstraintSnippets(parameterBody);
if (parameterConstraints.length > 0) {
parameterEntry.constraints = parameterConstraints;
}
if (argumentsMap[name]) {
console.log(`Warning: Duplicate parameter name "${name}" encountered in command ${commandName} for cluster ${clusterName} (${contextLabel}). Overwriting previous entry.`);
}
argumentsMap[name] = parameterEntry;
}
};
processTag('arg');
processTag('field');
return argumentsMap;
};
const parseCommandsBlock = (xmlContent, clusterName, contextLabel) => {
const commandRegex = /<command\b[^>]*?(?:\/\s*>|>[\s\S]*?<\/command>)/gi;
if (!commandRegex.test(xmlContent)) {
return {};
}
commandRegex.lastIndex = 0;
const commands = {};
let commandMatch;
while ((commandMatch = commandRegex.exec(xmlContent)) !== null) {
const fragment = commandMatch[0];
const openingMatch = fragment.match(/<command\b[^>]*>/i);
if (!openingMatch) {
throw new Error(`Unable to parse command definition for cluster ${clusterName} (${contextLabel}).`);
}
const commandAttributes = parseAttributes(openingMatch[0]);
const { name, code, summary = '', ...rest } = commandAttributes;
if (!name) {
throw new Error(`Command without a name encountered in cluster ${clusterName} (${contextLabel}).`);
}
const commandEntry = { name };
if (code !== undefined) {
commandEntry.id = parseNumericValue(code);
}
if (summary) {
commandEntry.summary = summary;
}
for (const [key, value] of Object.entries(rest)) {
const normalizedKey = toCamelCase(key);
commandEntry[normalizedKey] = parseScalarValue(value);
}
let commandBody = '';
if (!fragment.trimEnd().endsWith('/>')) {
commandBody = fragment.slice(openingMatch[0].length, fragment.length - '</command>'.length);
}
const directiveSegments = [];
const descriptionMatch = commandBody.match(/<description>([\s\S]*?)<\/description>/i);
if (descriptionMatch) {
const [matchText, body] = descriptionMatch;
const start = descriptionMatch.index ?? commandBody.indexOf(matchText);
const end = start + matchText.length;
directiveSegments.push({ start, end });
const description = body.replace(/\s+/g, ' ').trim();
if (description) {
commandEntry.description = description;
}
}
const argumentsMap = parseCommandArguments(commandBody, name, clusterName, contextLabel, directiveSegments);
if (Object.keys(argumentsMap).length > 0) {
commandEntry.arguments = argumentsMap;
}
const accessRegex = /<access\b[^>]*?(?:\/\s*>|>[\s\S]*?<\/access>)/gi;
let accessMatch;
while ((accessMatch = accessRegex.exec(commandBody)) !== null) {
directiveSegments.push({ start: accessMatch.index, end: accessRegex.lastIndex });
const accessAttributes = parseAttributes(accessMatch[0]);
for (const [key, value] of Object.entries(accessAttributes)) {
const propertyKey = prefixDirectiveKey('access', key);
commandEntry[propertyKey] = parseScalarValue(value);
}
}
const qualityRegex = /<quality\b[^>]*?(?:\/\s*>|>[\s\S]*?<\/quality>)/gi;
let qualityMatch;
while ((qualityMatch = qualityRegex.exec(commandBody)) !== null) {
directiveSegments.push({ start: qualityMatch.index, end: qualityRegex.lastIndex });
const qualityAttributes = parseAttributes(qualityMatch[0]);
for (const [key, value] of Object.entries(qualityAttributes)) {
const propertyKey = prefixDirectiveKey('quality', key);
commandEntry[propertyKey] = parseScalarValue(value);
}
}