This repository was archived by the owner on Jan 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathparseFileContents.js
More file actions
2577 lines (2424 loc) · 137 KB
/
parseFileContents.js
File metadata and controls
2577 lines (2424 loc) · 137 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
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const LUISObjNameEnum = require('./../utils/enums/luisobjenum');
const PARSERCONSTS = require('./../utils/enums/parserconsts');
const builtInTypes = require('./../utils/enums/luisbuiltintypes');
const helpers = require('./../utils/helpers');
const SectionType = require('./../utils/enums/lusectiontypes');
const chalk = require('chalk');
const url = require('url');
const retCode = require('./../utils/enums/CLI-errors');
const parserObj = require('./classes/parserObject');
const qnaListObj = require('./../qna/qnamaker/qnaList');
const qnaMetaDataObj = require('./../qna/qnamaker/qnaMetaData');
const helperClass = require('./classes/hclasses');
const deepEqual = require('deep-equal');
const exception = require('./../utils/exception');
const qnaAlterations = require('./../qna/alterations/alterations');
const axios = require('axios');
const qnaFile = require('./../qna/qnamaker/qnaFiles');
const fileToParse = require('./classes/filesToParse');
const luParser = require('./luParser');
const {BuildDiagnostic, DiagnosticSeverity} = require('./diagnostic');
const EntityTypeEnum = require('./../utils/enums/luisEntityTypes');
const luisEntityTypeMap = require('./../utils/enums/luisEntityTypeNameMap');
const qnaContext = require('../qna/qnamaker/qnaContext');
const qnaPrompt = require('../qna/qnamaker/qnaPrompt');
const LUResource = require('./luResource');
const InvalidCharsInIntentOrEntityName = require('./../utils/enums/invalidchars').InvalidCharsInIntentOrEntityName;
const httpsProxy = require('../utils/httpsProxy')
axios.interceptors.request.use(httpsProxy)
const plAllowedTypes = ["composite", "ml"];
const featureTypeEnum = {
featureToModel: 'modelName',
modelToFeature: 'featureName'
};
const featureProperties = {
entityFeatureToModel : {
'simple': 'Entity Extractor',
'list' : 'Closed List Entity Extractor',
'prebuilt': 'Prebuilt Entity Extractor',
'composite': 'Composite Entity Extractor',
'regex': 'Regex Entity Extractor',
'ml': 'Entity Extractor'
},
intentFeatureToModel: 'Intent Classifier',
phraseListFeature: 'phraselist'
}
const INTENTTYPE = 'intent';
const PLCONSTS = {
DISABLED : 'disabled',
ENABLEDFORALLMODELS: 'enabledforallmodels',
DISABLEDFORALLMODELS: 'disabledforallmodels',
INTERCHANGEABLE: '(interchangeable)'
};
const defaultConfig = {
enablePattern: true,
enableMLEntities: true,
enableListEntities: true,
enableCompositeEntities: true,
enablePrebuiltEntities: true,
enableRegexEntities: true,
enablePhraseLists: true,
enableFeatures: true,
enableModelDescription: true,
enableExternalReferences: true,
enableComments: true
};
const parseFileContentsModule = {
/**
* Main parser code to parse current file contents into LUIS and QNA sections.
* @param {string} fileContent current file content
* @param {boolean} log indicates if we need verbose logging.
* @param {string} locale LUIS locale code
* @returns {parserObj} Object with that contains list of additional files to parse, parsed LUIS object and parsed QnA object
* @throws {exception} Throws on errors. exception object includes errCode and text.
*/
parseFile: async function (fileContent, log, locale, config) {
fileContent = helpers.sanitizeNewLines(fileContent);
config = config || {};
config = {...defaultConfig, ...config};
let parsedContent = new parserObj();
if (fileContent === '') {
return parsedContent;
}
await parseLuAndQnaWithAntlr(parsedContent, fileContent.toString(), log, locale, config);
return parsedContent;
},
/**
* Validate resource based on config.
* @param {LUResource} originalResource Original parsed lu or qna resource
* @param {any} config Features config
* @returns {any[]} Diagnostic errors returned
*/
validateResource: function (originalResource, config) {
config = config || {};
config = {...defaultConfig, ...config};
let resource = JSON.parse(JSON.stringify(originalResource));
if (resource.Errors.filter(error => (error && error.Severity && error.Severity === DiagnosticSeverity.ERROR)).length > 0) {
return []
}
let errors = []
try {
let parsedContent = new parserObj();
// parse model info section
let enableMergeIntents = parseAndHandleModelInfoSection(parsedContent, resource, false, config);
// validate reference section
validateImportSection(resource, config);
// parse nested intent section
parseAndHandleNestedIntentSection(resource, enableMergeIntents);
GetEntitySectionsFromSimpleIntentSections(resource);
// parse entity definition v2 section
let featuresToProcess = parseAndHandleEntityV2(parsedContent, resource, false, undefined, config);
// parse entity section
parseAndHandleEntitySection(parsedContent, resource, false, undefined, config);
// validate simple intent section
parseAndHandleSimpleIntentSection(parsedContent, resource, config)
if (featuresToProcess && featuresToProcess.length > 0) {
parseFeatureSections(parsedContent, featuresToProcess, config);
}
} catch(e) {
if (e instanceof exception && e.diagnostics) {
errors.push(...e.diagnostics)
} else {
errors.push(BuildDiagnostic({
message: e.message || e.text
}))
}
}
return errors
},
/**
* Helper function to add an item to collection if it does not exist
* @param {object} collection contents of the current collection
* @param {LUISObjNameEnum} type item type
* @param {object} value value of the current item to examine and add
* @returns {void} nothing
*/
addItemIfNotPresent: function (collection, type, value) {
let hasValue = false;
for (let i in collection[type]) {
if (collection[type][i].name === value) {
hasValue = true;
break;
}
}
if (!hasValue) {
let itemObj = {};
itemObj.name = value;
if (type == LUISObjNameEnum.PATTERNANYENTITY) {
itemObj.explicitList = [];
}
if (type !== LUISObjNameEnum.INTENT) {
itemObj.roles = [];
}
collection[type].push(itemObj);
}
},
/**
* Helper function to add an item to collection if it does not exist
* @param {object} collection contents of the current collection
* @param {LUISObjNameEnum} type item type
* @param {object} value value of the current item to examine and add
* @param {string []} roles possible roles to add to the item
* @returns {void} nothing
*/
addItemOrRoleIfNotPresent: function (collection, type, value, roles) {
let existingItem = collection[type].filter(item => item.name == value);
if (existingItem.length !== 0) {
// see if the role exists and if so, merge
mergeRoles(existingItem[0].roles, roles);
} else {
let itemObj = {};
itemObj.name = value;
if (type == LUISObjNameEnum.PATTERNANYENTITY) {
itemObj.explicitList = [];
}
if (type == LUISObjNameEnum.COMPOSITES) {
itemObj.children = [];
}
if (type !== LUISObjNameEnum.INTENT) {
itemObj.roles = roles;
}
collection[type].push(itemObj);
}
}
};
/**
* Main parser code to parse current file contents into LUIS and QNA sections.
* @param {parserObj} Object with that contains list of additional files to parse, parsed LUIS object and parsed QnA object
* @param {string} fileContent current file content
* @param {boolean} log indicates if we need verbose logging.
* @param {string} locale LUIS locale code
* @throws {exception} Throws on errors. exception object includes errCode and text.
*/
const parseLuAndQnaWithAntlr = async function (parsedContent, fileContent, log, locale, config) {
fileContent = helpers.sanitizeNewLines(fileContent);
let luResource = luParser.parse(fileContent, undefined, config);
if (luResource.Errors && luResource.Errors.length > 0) {
if (log) {
var warns = luResource.Errors.filter(error => (error && error.Severity && error.Severity === DiagnosticSeverity.WARN));
if (warns.length > 0) {
process.stdout.write(warns.map(warn => warn.toString()).join('\n').concat('\n'));
}
}
var errors = luResource.Errors.filter(error => (error && error.Severity && error.Severity === DiagnosticSeverity.ERROR));
if (errors.length > 0) {
throw (new exception(retCode.errorCode.INVALID_LINE, errors.map(error => error.toString()).join('\n'), errors));
}
}
// parse model info section
let enableMergeIntents = parseAndHandleModelInfoSection(parsedContent, luResource, log, config);
// parse reference section
await parseAndHandleImportSection(parsedContent, luResource, config);
// parse nested intent section
parseAndHandleNestedIntentSection(luResource, enableMergeIntents);
GetEntitySectionsFromSimpleIntentSections(luResource);
// parse entity definition v2 section
let featuresToProcess = parseAndHandleEntityV2(parsedContent, luResource, log, locale, config);
// parse entity section
parseAndHandleEntitySection(parsedContent, luResource, log, locale, config);
// parse simple intent section
parseAndHandleSimpleIntentSection(parsedContent, luResource, config);
// parse qna section
await parseAndHandleQnaSection(parsedContent, luResource);
if (featuresToProcess && featuresToProcess.length > 0) {
parseFeatureSections(parsedContent, featuresToProcess, config);
}
validateNDepthEntities(parsedContent.LUISJsonStructure.entities, parsedContent.LUISJsonStructure.flatListOfEntityAndRoles, parsedContent.LUISJsonStructure.intents);
// Update intent and entities with phrase lists if any
updateIntentAndEntityFeatures(parsedContent.LUISJsonStructure);
helpers.checkAndUpdateVersion(parsedContent.LUISJsonStructure);
}
const updateIntentAndEntityFeatures = function(luisObj) {
let plForAll = luisObj.model_features.filter(item => item.enabledForAllModels == undefined || item.enabledForAllModels == true);
plForAll.forEach(pl => {
luisObj.intents.forEach(intent => updateFeaturesWithPL(intent, pl.name));
luisObj.entities.forEach(entity => updateFeaturesWithPL(entity, pl.name));
})
}
const updateFeaturesWithPL = function(collection, plName) {
if (collection === null || collection === undefined) return;
if (collection.hasOwnProperty("features")) {
if (Array.isArray(collection.features) && collection.features.find(i => i.featureName == plName) === undefined) {
collection.features.push(new helperClass.featureToModel(plName, featureProperties.phraseListFeature));
}
} else {
collection.features = [new helperClass.featureToModel(plName, featureProperties.phraseListFeature)];
}
}
/**
* Helper to update final LUIS model based on labelled nDepth entities.
* @param {Object []} utterances
* @param {Object []} entities
*/
const updateModelBasedOnNDepthEntities = function(utterances, entities) {
// filter to all utterances that have a labelled entity
let utterancesWithLabels = utterances.filter(utterance => utterance.entities && utterance.entities.length !== 0);
utterancesWithLabels.forEach(utterance => {
utterance.entities.forEach(entityInUtterance => {
// find this entity's root. There can be multiple and if there are, we need to delete the one that does not have children.
let entityFoundInMaster = [];
entities.forEach((entity, idx) => {
if (entity.name == entityInUtterance.entity) {
entityFoundInMaster.push({id: idx, entityRoot: entity, path: '/'});
}
let entityPath = findEntityPath(entity, entityInUtterance.entity, "");
if (entityPath !== "") {
entityFoundInMaster.push({id: idx, entityRoot: entity, path: entityPath});
}
});
let isParentLabelled = false;
entityFoundInMaster.forEach(entityInMaster => {
let splitPath = entityInMaster.path.split("/").filter(item => item.trim() !== "");
if (entityFoundInMaster.length > 1 && splitPath.length === 0 && (!entityInMaster.entityRoot.children || entityInMaster.entityRoot.children.length === 0)) {
// this child needs to be removed. Note: There can only be at most one more entity due to utterance validation rules.
entities.splice(entityInMaster.id, 1);
} else {
if (isParentLabelled === false) {
let rSplitPath = splitPath.reverse();
rSplitPath.splice(0, 1);
rSplitPath.forEach(parent => {
// Ensure each parent is also labelled in this utterance
let parentLabelled = utterance.entities.find(entityUtt => entityUtt.entity == parent);
if (!parentLabelled) {
const errorMsg = `Every child entity labelled in an utterance must have its parent labelled in that utterance. Parent "${parent}" for child "${entityInUtterance.entity}" is not labelled in utterance "${utterance.text}" for intent "${utterance.intent}".`;
const error = BuildDiagnostic({
message: errorMsg
});
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
} else {
isParentLabelled = true;
}
})
}
}
})
})
})
}
/**
* Helper function to recursively find the path to a child entity
* @param {Object} obj
* @param {String} entityName
* @param {String} path
*/
const findEntityPath = function(obj, entityName, path) {
path = path || "";
var fullpath = "";
if (obj.name === entityName) {
return path;
} else if (obj.children && obj.children.length !== 0) {
obj.children.forEach(child => {
fullpath = findEntityPath(child, entityName, path + "/" + obj.name + "/" + child.name) || fullpath;
})
}
return fullpath;
}
/**
* Helper function to validate and update nDepth entities
* @param {Object[]} collection
* @param {Object[]} entitiesAndRoles
* @param {Object[]} intentsCollection
*/
const validateNDepthEntities = function(collection, entitiesAndRoles, intentsCollection) {
(collection || []).forEach(child => {
if(child.instanceOf) {
let baseEntityFound = entitiesAndRoles.find(i => i.name == child.instanceOf);
if (!baseEntityFound) {
let errorMsg = `Invalid child entity definition found. No definition for "${child.instanceOf}" in child entity definition "${child.context.definition}".`;
const error = BuildDiagnostic({
message: errorMsg,
line: child.context.line
});
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
// base type can only be a list or regex or prebuilt.
if (![EntityTypeEnum.LIST, EntityTypeEnum.REGEX, EntityTypeEnum.PREBUILT, EntityTypeEnum.ML].includes(baseEntityFound.type)) {
let errorMsg = `Invalid child entity definition found. "${child.instanceOf}" is of type "${baseEntityFound.type}" in child entity definition "${child.context.definition}". Child cannot be only be an instance of "${EntityTypeEnum.LIST}, ${EntityTypeEnum.REGEX} or ${EntityTypeEnum.PREBUILT}.`;
const error = BuildDiagnostic({
message: errorMsg,
line: child.context.line
});
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
}
if (child.features) {
let featureHandled = false;
(child.features || []).forEach((feature, idx) => {
if (typeof feature === "object") return;
featureHandled = false;
feature = feature.replace(/["']/gi, '');
let featureExists = entitiesAndRoles.find(i => (i.name == feature || i.name == `${feature}(interchangeable)`));
if (featureExists) {
// is feature phrase list?
if (featureExists.type == EntityTypeEnum.PHRASELIST) {
child.features[idx] = new helperClass.featureToModel(feature, featureProperties.phraseListFeature);
featureHandled = true;
} else if (featureExists.type == EntityTypeEnum.PATTERNANY) {
let errorMsg = `Invalid child entity definition found. "${feature}" is of type "${EntityTypeEnum.PATTERNANY}" in child entity definition "${child.context.definition}". Child cannot include a usesFeature of type "${EntityTypeEnum.PATTERNANY}".`;
const error = BuildDiagnostic({
message: errorMsg,
line: child.context.line
});
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
} else {
child.features[idx] = new helperClass.modelToFeature(feature, featureProperties.entityFeatureToModel[featureExists.type]);
featureHandled = true;
}
}
if (!featureHandled) {
// find feature as intent
let intentFeatureExists = intentsCollection.find(i => i.name == feature);
if (intentFeatureExists) {
child.features[idx] = new helperClass.modelToFeature(feature, featureProperties.intentFeatureToModel);
featureHandled = true;
} else {
let errorMsg = `Invalid child entity definition found. No definition found for "${feature}" in child entity definition "${child.context.definition}". Features must be defined before they can be added to a child.`;
const error = BuildDiagnostic({
message: errorMsg,
line: child.context.line
});
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
}
})
}
if (child.children) {
validateNDepthEntities(child.children, entitiesAndRoles, intentsCollection);
}
if (child.context) {
delete child.context
}
if (child.features === "") {
delete child.features
}
})
};
/**
* Helper function to validate if the requested feature addition is valid.
* @param {String} srcItemType
* @param {String} srcItemName
* @param {String} tgtFeatureType
* @param {String} tgtFeatureName
* @param {Range} range
*/
const validateFeatureAssignment = function(srcItemType, srcItemName, tgtFeatureType, tgtFeatureName, range) {
switch(srcItemType) {
case INTENTTYPE:
case EntityTypeEnum.SIMPLE:
case EntityTypeEnum.ML:
case EntityTypeEnum.COMPOSITE:
// can use everything as a feature except pattern.any
if (tgtFeatureType === EntityTypeEnum.PATTERNANY) {
let errorMsg = `'patternany' entity cannot be added as a feature. Invalid definition found for "@ ${srcItemType} ${srcItemName} usesFeature ${tgtFeatureName}"`;
let error = BuildDiagnostic({
message: errorMsg,
range: range
})
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
break;
default:
// cannot have any features assigned
let errorMsg = `Invalid definition found for "@ ${srcItemType} ${srcItemName} usesFeature ${tgtFeatureName}". usesFeature is only available for intent, ${plAllowedTypes.join(', ')}`;
let error = BuildDiagnostic({
message: errorMsg,
range: range
})
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
break;
}
}
/**
* Helper function to add features to the parsed content scope.
* @param {Object} tgtItem
* @param {String} feature
* @param {String} featureType
* @param {Object} range
*/
const addFeatures = function(tgtItem, feature, featureType, range, featureProperties, featureIsPhraseList = false) {
// target item cannot have the same name as the feature name
// the only exception case is intent and entity can have same name with phraseList feature
if (tgtItem.name === feature && !featureIsPhraseList) {
// Item must be defined before being added as a feature.
let errorMsg = `Source and target cannot be the same for usesFeature. e.g. x usesFeature x is invalid. "${tgtItem.name}" usesFeature "${feature}" is invalid.`;
let error = BuildDiagnostic({
message: errorMsg,
range: range
})
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
let featureToModelAlreadyDefined = (tgtItem.features || []).find(item => item.featureName == feature);
let modelToFeatureAlreadyDefined = (tgtItem.features || []).find(item => item.modelName == feature);
switch (featureType) {
case featureTypeEnum.featureToModel: {
if (tgtItem.features) {
if (!featureToModelAlreadyDefined) tgtItem.features.push(new helperClass.featureToModel(feature, featureProperties));
} else {
tgtItem.features = new Array(new helperClass.featureToModel(feature, featureProperties));
}
break;
}
case featureTypeEnum.modelToFeature: {
if (tgtItem.features) {
if (!modelToFeatureAlreadyDefined){
tgtItem.features.push(new helperClass.modelToFeature(feature, featureProperties));
}
} else {
tgtItem.features = new Array(new helperClass.modelToFeature(feature, featureProperties));
}
break;
}
default:
break;
}
}
/**
* Helper function to handle usesFeature definitions
* @param {Object} parsedContent
* @param {Object} featuresToProcess
*/
const parseFeatureSections = function(parsedContent, featuresToProcess, config) {
if (!config.enableFeatures) {
const error = BuildDiagnostic({
message: 'Do not support Features. Please make sure enableFeatures is set to true.',
});
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
// We are only interested in extracting features and setting things up here.
(featuresToProcess || []).forEach(section => {
if (section.Type === INTENTTYPE) {
// Intents can only have features and nothing else.
if (section.Roles) {
let errorMsg = `Intents can only have usesFeature and nothing else. Invalid definition for "${section.Name}".`;
let error = BuildDiagnostic({
message: errorMsg,
range: section.Range
})
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
if (!section.Features) return;
// verify intent exists
section.Name = section.Name.replace(/[\'\"]/g, "");
let intentExists = parsedContent.LUISJsonStructure.intents.find(item => item.name === section.Name);
if (intentExists !== undefined) {
// verify the list of features requested have all been defined.
let featuresList = section.Features.split(/[,;]/g).map(item => item.trim().replace(/^[\'\"]|[\'\"]$/g, ""));
let featuresVisited = new Set();
(featuresList || []).forEach(feature => {
// usually phraseList has higher priority when searching the existing entities as phraseList is more likely to be used as feature
// but when a ml entity and a phraseList have same name, this assumption will cause a problem in situation that
// users actually want to specify the ml entity as feature rather than phraseList
// currently we can not distinguish them in lu file, as for @ intent A usesFeature B, B can be a ml entity or a phraseList with same name
// the lu format for usesFeatures defintion need to be updated if we want to resolve this confusion completely
let entityExists = (parsedContent.LUISJsonStructure.flatListOfEntityAndRoles || []).find(item => (item.name == feature || item.name == `${feature}(interchangeable)`) && item.type == EntityTypeEnum.PHRASELIST);
// if phraseList is not matched to the feature, search other non phraseList entities
// or this intent use multiple features with same name, e.g., @ intent A usesFeatures B, B.
// and current loop is processiong the second feature B
// this is allowed in luis portal, you can add ml entity and phraseList features of same name to an intent
// the exported intent useFeatures will have two features with same name listed, just like above sample @ intent A usesFeatures B, B
if (!entityExists || featuresVisited.has(feature)) {
entityExists = (parsedContent.LUISJsonStructure.flatListOfEntityAndRoles || []).find(item => item.name == feature && item.type !== EntityTypeEnum.PHRASELIST);
}
if (!featuresVisited.has(feature)) featuresVisited.add(feature);
let featureIntentExists = (parsedContent.LUISJsonStructure.intents || []).find(item => item.name == feature);
if (entityExists) {
if (entityExists.type === EntityTypeEnum.PHRASELIST) {
// de-dupe and add features to intent.
validateFeatureAssignment(section.Type, section.Name, entityExists.type, feature, section.Range);
addFeatures(intentExists, feature, featureTypeEnum.featureToModel, section.Range, featureProperties.phraseListFeature, true);
// set enabledForAllModels on this phrase list
let plEnity = parsedContent.LUISJsonStructure.model_features.find(item => item.name == feature);
if (plEnity.enabledForAllModels === undefined) plEnity.enabledForAllModels = false;
} else {
// de-dupe and add model to intent.
validateFeatureAssignment(section.Type, section.Name, entityExists.type, feature, section.Range);
addFeatures(intentExists, feature, featureTypeEnum.modelToFeature, section.Range, featureProperties.entityFeatureToModel[entityExists.type]);
}
} else if (featureIntentExists) {
// Add intent as a feature to another intent
validateFeatureAssignment(section.Type, section.Name, INTENTTYPE, feature, section.Range);
addFeatures(intentExists, feature, featureTypeEnum.modelToFeature, section.Range, featureProperties.intentFeatureToModel);
} else {
// Item must be defined before being added as a feature.
let errorMsg = `Features must be defined before assigned to an intent. No definition found for feature "${feature}" in usesFeature definition for intent "${section.Name}"`;
let error = BuildDiagnostic({
message: errorMsg,
range: section.Range
})
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
})
} else {
let errorMsg = `Features can only be added to intents that have a definition. Invalid feature definition found for intent "${section.Name}".`;
let error = BuildDiagnostic({
message: errorMsg,
range: section.Range
})
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
} else {
// handle as entity
if (section.Features) {
let featuresList = section.Features.split(/[,;]/g).map(item => item.trim());
// Find the source entity from the collection and get its type
let srcEntityInFlatList = (parsedContent.LUISJsonStructure.flatListOfEntityAndRoles || []).find(item => item.name == section.Name);
let entityType = srcEntityInFlatList ? srcEntityInFlatList.type : undefined;
let featuresVisited = new Set();
(featuresList || []).forEach(feature => {
feature = feature.replace(/[\'\"]/g, "");
// usually phraseList has higher priority when searching the existing entities as phraseList is more likely to be used as feature to a entity
// but when a ml entity and a phraseList have same name, this assumption will cause a problem in situation that
// users actually want to specify the ml entity as feature rather than phraseList
// currently we can not distinguish them in lu file, as for @ ml A usesFeature B, B can be another ml entity or a phraseList with same name
// the lu format for usesFeatures defintion need to be updated if we want to resolve this confusion completely
let featureExists = (parsedContent.LUISJsonStructure.flatListOfEntityAndRoles || []).find(item => (item.name == feature || item.name == `${feature}(interchangeable)`) && item.type == EntityTypeEnum.PHRASELIST);
// if phraseList is not matched to the feature, search other non phraseList entities
// or this intent use multiple features with same name, e.g., @ intent A usesFeatures B, B.
// and current loop is processiong the second feature B
// this is allowed in luis portal, you can add ml entity and phraseList features of same name to an intent
// the exported intent useFeatures will have two features with same name listed, just like above sample @ intent A usesFeatures B, B
if (!featureExists || featuresVisited.has(feature)) {
featureExists = (parsedContent.LUISJsonStructure.flatListOfEntityAndRoles || []).find(item => item.name == feature && item.type !== EntityTypeEnum.PHRASELIST);
}
if (!featuresVisited.has(feature)) featuresVisited.add(feature);
let featureIntentExists = (parsedContent.LUISJsonStructure.intents || []).find(item => item.name == feature);
// find the entity based on its type.
let srcEntity = (parsedContent.LUISJsonStructure[luisEntityTypeMap[entityType]] || []).find(item => item.name == section.Name);
if (featureExists) {
if (featureExists.type === EntityTypeEnum.PHRASELIST) {
// de-dupe and add features to intent.
validateFeatureAssignment(entityType, section.Name, featureExists.type, feature, section.Range);
addFeatures(srcEntity, feature, featureTypeEnum.featureToModel, section.Range, featureProperties.phraseListFeature, true);
// set enabledForAllModels on this phrase list
let plEnity = parsedContent.LUISJsonStructure.model_features.find(item => item.name == feature);
if (plEnity.enabledForAllModels === undefined) plEnity.enabledForAllModels = false;
} else {
// de-dupe and add model to intent.
validateFeatureAssignment(entityType, section.Name, featureExists.type, feature, section.Range);
addFeatures(srcEntity, feature, featureTypeEnum.modelToFeature, section.Range, featureProperties.entityFeatureToModel[featureExists.type]);
}
} else if (featureIntentExists) {
// Add intent as a feature to another intent
validateFeatureAssignment(entityType, section.Name, INTENTTYPE, feature, section.Range);
addFeatures(srcEntity, feature, featureTypeEnum.modelToFeature, section.Range, featureProperties.intentFeatureToModel);
} else {
addFeatures(srcEntity, feature, featureTypeEnum.modelToFeature, section.Range, featureProperties.intentFeatureToModel);
}
});
}
}
});
// Circular dependency for features is not allowed. E.g. A usesFeature B usesFeature A is not valid.
verifyNoCircularDependencyForFeatures(parsedContent);
}
/**
* Helper function to update a list of dependencies for usesFeature
* @param {String} type
* @param {Object} parsedContent
* @param {Object} dependencyList
*/
const updateDependencyList = function(type, parsedContent, dependencyList) {
// go through intents and capture dependency list
(parsedContent.LUISJsonStructure[type] || []).forEach(itemOfType => {
let srcName = itemOfType.name;
let copySrc, copyValue;
if (itemOfType.features) {
(itemOfType.features || []).forEach(featureObj => {
let feature = featureObj.modelName ? featureObj.modelName : featureObj.featureName;
let type = featureObj.modelType ? featureObj.modelType : featureObj.featureType;
// find any items where this feature is the target
let featureDependencyEx = dependencyList.filter(item => srcName == (item.value ? item.value.slice(-1)[0].feature : undefined));
(featureDependencyEx || []).forEach(item => {
item.key = `${item.key.split('::')[0]}::${feature}`;
item.value.push({feature, type});
})
// find any items where this feature is the source
featureDependencyEx = dependencyList.find(item => feature == (item.value ? item.value.slice(0)[0] : undefined));
if (featureDependencyEx) {
copySrc = featureDependencyEx.key.split('::')[1];
copyValue = featureDependencyEx.value.slice(1);
}
let dependencyExists = dependencyList.find(item => item.key == `${srcName}::${feature}`);
if (!dependencyExists) {
let lKey = copySrc ? `${srcName}::${copySrc}` : `${srcName}::${feature}`;
let lValue = [srcName, {feature, type}];
if (copyValue) copyValue.forEach(item => lValue.push(item));
dependencyList.push({
key : lKey,
value : lValue
})
} else {
dependencyExists.key = `${dependencyExists.key.split('::')[0]}::${feature}`;
dependencyExists.value.push({feature, type});
}
let circularItemFound = dependencyList.find(item => item.value
&& item.value.slice(0)[0] == item.value.slice(-1)[0].feature
&& item.value.slice(-1)[0].type !== featureProperties.phraseListFeature);
if (circularItemFound) {
const errorMsg = `Circular dependency found for usesFeature. ${circularItemFound.value.map(v => v.feature ? v.feature : v).join(' -> ')}`;
const error = BuildDiagnostic({
message: errorMsg
});
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
})
}
});
}
/**
* Helper function to verify there are no circular dependencies in the parsed content.
* @param {Object} parsedContent
*/
const verifyNoCircularDependencyForFeatures = function(parsedContent) {
let dependencyList = [];
updateDependencyList(LUISObjNameEnum.INTENT, parsedContent, dependencyList);
updateDependencyList(LUISObjNameEnum.ENTITIES, parsedContent, dependencyList);
updateDependencyList(LUISObjNameEnum.CLOSEDLISTS, parsedContent, dependencyList);
updateDependencyList(LUISObjNameEnum.COMPOSITES, parsedContent, dependencyList);
updateDependencyList(LUISObjNameEnum.PATTERNANYENTITY, parsedContent, dependencyList);
updateDependencyList(LUISObjNameEnum.PREBUILT, parsedContent, dependencyList);
updateDependencyList(LUISObjNameEnum.REGEX, parsedContent, dependencyList);
}
/**
* Reference parser code to parse reference section.
* @param {parserObj} Object with that contains list of additional files to parse, parsed LUIS object and parsed QnA object
* @param {LUResouce} luResource resources extracted from lu file content
* @throws {exception} Throws on errors. exception object includes errCode and text.
*/
const parseAndHandleImportSection = async function (parsedContent, luResource, config) {
// handle reference
let luImports = luResource.Sections.filter(s => s.SectionType === SectionType.IMPORTSECTION);
if (luImports && luImports.length > 0) {
if (!config.enableExternalReferences) {
const error = BuildDiagnostic({
message: 'Do not support External References. Please make sure enableExternalReferences is set to true.'
});
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
let references = luResource.Sections.filter(s => s.SectionType === SectionType.REFERENCESECTION);
for (const luImport of luImports) {
let linkValueText = luImport.Description.replace('[', '').replace(']', '');
let linkValue = luImport.Path.replace('(', '').replace(')', '');
let parseUrl = url.parse(linkValue);
if (parseUrl.host || parseUrl.hostname) {
let options = { method: 'HEAD' };
let response;
try {
response = await axios({
method: 'HEAD',
url: linkValue
});
} catch (err) {
// throw, invalid URI
let errorMsg = `URI: "${linkValue}" appears to be invalid. Please double check the URI or re-try this parse when you are connected to the internet.`;
let error = BuildDiagnostic({
message: errorMsg,
range: luImport.Range
})
throw (new exception(retCode.errorCode.INVALID_URI, error.toString(), [error]));
}
if (response.status !== 200) {
let errorMsg = `URI: "${linkValue}" appears to be invalid. Please double check the URI or re-try this parse when you are connected to the internet.`;
let error = BuildDiagnostic({
message: errorMsg,
range: luImport.Range
})
throw (new exception(retCode.errorCode.INVALID_URI, error.toString(), [error]));
}
let contentType = response.headers['content-type'];
if (!contentType.includes('text/html')) {
if (parseUrl.pathname.toLowerCase().endsWith('.lu') || parseUrl.pathname.toLowerCase().endsWith('.qna')) {
parsedContent.additionalFilesToParse.push(new fileToParse(linkValue));
} else {
parsedContent.qnaJsonStructure.files.push(new qnaFile(linkValue, linkValueText));
}
} else {
parsedContent.qnaJsonStructure.urls.push(linkValue);
}
} else {
if (parseInt(linkValue, 10).toString() === linkValue) {
let foundReference = references.find(refer => refer.ReferenceId === linkValue)
if (foundReference) {
linkValue = foundReference.Path
} else {
let errorMsg = `Cannot find reference "${linkValue}" when resolving import "${luImport.Description}${luImport.Path}".`;
let error = BuildDiagnostic({
message: errorMsg,
range: luImport.Range
})
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
}
parsedContent.additionalFilesToParse.push(new fileToParse(linkValue));
}
}
}
}
/**
* Reference parser code to parse reference section.
* @param {LUResouce} luResource resources extracted from lu file content
* @throws {exception} Throws on errors. exception object includes errCode and text.
*/
const validateImportSection = function (luResource, config) {
// handle reference
let luImports = luResource.Sections.filter(s => s.SectionType === SectionType.IMPORTSECTION);
if (luImports && luImports.length > 0) {
if (!config.enableExternalReferences) {
const error = BuildDiagnostic({
message: 'Do not support External References. Please make sure enableExternalReferences is set to true.'
});
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
}
}
/**
* Helper function to handle @ reference in patterns
* @param {String} utterance
* @param {String []} entitiesFound
* @param {Object []} flatEntityAndRoles
*/
const handleAtForPattern = function(utterance, entitiesFound, flatEntityAndRoles) {
if (utterance.match(/{@/g)) {
utterance = utterance.replace(/{@/g, '{');
entitiesFound.forEach(entity => {
if (entity.entity.match(/^@/g)) {
entity = handleAtPrefix(entity, flatEntityAndRoles);
if (entity.entity && entity.role) {
utterance = utterance.replace(`{${entity.role}}`, `{${entity.entity}:${entity.role}}`);
}
}
});
}
return utterance;
}
/**
* Helper function to handle @ entity or @ role reference in utterances.
* @param {Object} entity
* @param {Object []} flatEntityAndRoles
*/
const handleAtPrefix = function(entity, flatEntityAndRoles) {
if (entity.entity.match(/^@/g)) {
entity.entity = entity.entity.replace(/^@/g, '').trim();
if (flatEntityAndRoles) {
// find the entity as a match by name
let entityMatch = flatEntityAndRoles.find(item => item.entityName == entity.entity);
if (entityMatch !== undefined) {
return entity;
}
// find the entity as a match by role
let roleMatch = flatEntityAndRoles.find(item => item.roles.includes(entity.entity));
if (roleMatch !== undefined) {
// we have a role match.
entity.role = entity.entity;
entity.entity = roleMatch.name;
return entity;
}
}
}
return entity;
}
/**
* Intent parser code to parse intent section.
* @param {LUResouce} luResource resources extracted from lu file content
* @param {boolean} enableMergeIntents enable functionality to merge intents in nested intent section or not
* @throws {exception} Throws on errors. exception object includes errCode and text.
*/
const parseAndHandleNestedIntentSection = function (luResource, enableMergeIntents) {
// handle nested intent section
let sections = luResource.Sections.filter(s => s.SectionType === SectionType.NESTEDINTENTSECTION);
if (sections && sections.length > 0) {
sections.forEach(section => {
if (enableMergeIntents) {
let mergedIntentSection = section.SimpleIntentSections[0];
mergedIntentSection.Name = section.Name;
mergedIntentSection.Range = section.Range;
for (let idx = 1; idx < section.SimpleIntentSections.length; idx++) {
mergedIntentSection.UtteranceAndEntitiesMap = mergedIntentSection.UtteranceAndEntitiesMap.concat(section.SimpleIntentSections[idx].UtteranceAndEntitiesMap);
mergedIntentSection.Entities = mergedIntentSection.Entities.concat(section.SimpleIntentSections[idx].Entities);
}
luResource.Sections.push(mergedIntentSection);
} else {
section.SimpleIntentSections.forEach(subSection => {
subSection.Name = section.Name + '.' + subSection.Name;
luResource.Sections.push(subSection);
})
}
})
}
}
/**
* Intent parser code to parse intent section.
* @param {parserObj} Object with that contains list of additional files to parse, parsed LUIS object and parsed QnA object
* @param {LUResouce} luResource resources extracted from lu file content
* @throws {exception} Throws on errors. exception object includes errCode and text.
*/
const parseAndHandleSimpleIntentSection = function (parsedContent, luResource, config) {
// handle intent
let intents = luResource.Sections.filter(s => s.SectionType === SectionType.SIMPLEINTENTSECTION);
let hashTable = {}
if (intents && intents.length > 0) {
let references = luResource.Sections.filter(s => s.SectionType === SectionType.REFERENCESECTION);
for (const intent of intents) {
let intentName = intent.Name;
if (InvalidCharsInIntentOrEntityName.some(x => intentName.includes(x))) {
let errorMsg = `Invalid intent line, intent name ${intentName} cannot contain any of the following characters: [<, >, *, %, &, :, \\, $]`;
let error = BuildDiagnostic({
message: errorMsg,
line: intent.Range.Start.Line
})
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
// insert only if the intent is not already present.
addItemIfNotPresent(parsedContent.LUISJsonStructure, LUISObjNameEnum.INTENT, intentName);
for (const utteranceAndEntities of intent.UtteranceAndEntitiesMap) {
// add utterance
let utterance = utteranceAndEntities.utterance.trim();
let uttHash = helpers.hashCode(utterance);
// Fix for BF-CLI #122.
// Ensure only links are detected and passed on to be parsed.
if (helpers.isUtteranceLinkRef(utterance || '')) {
if (utterance.endsWith(']')) {
let index = utterance.lastIndexOf('[');
let referenceId = utterance.slice(index + 1, utterance.length - 1);
let reference = references.find(refer => refer.ReferenceId === referenceId)
if (!reference) {
let errorMsg = `Cannot find reference ${reference} when resolving utternace "${utteranceAndEntities.contextText}".`;
let error = BuildDiagnostic({
message: errorMsg,
range: utteranceAndEntities.range
})
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
utterance = `${utterance.slice(0, index)}(${reference.Path})`
}
let parsedLinkUriInUtterance = helpers.parseLinkURISync(utterance);
// examine and add these to filestoparse list.
parsedContent.additionalFilesToParse.push(new fileToParse(parsedLinkUriInUtterance.fileName, false, parsedLinkUriInUtterance.path));
}
(utteranceAndEntities.entities || []).forEach(entity => {
let errors = []
if (InvalidCharsInIntentOrEntityName.some(x => entity.entity.includes(x))) {
let errorMsg = `Invalid utterance line, entity name ${entity.entity} in this utterance cannot contain any of the following characters: [<, >, *, %, &, :, \\, $]`;
let error = BuildDiagnostic({
message: errorMsg,
range: utteranceAndEntities.range
});
errors.push(error);
}
if (errors.length > 0) {
throw (new exception(retCode.errorCode.INVALID_LINE, errors.map(error => error.toString()).join('\n'), errors));
}
})
if (utteranceAndEntities.entities.length > 0) {
let entitiesFound = utteranceAndEntities.entities;
let havePatternAnyEntity = entitiesFound.find(item => item.type == LUISObjNameEnum.PATTERNANYENTITY);
if (havePatternAnyEntity !== undefined) {
if (!config.enablePattern) {
const error = BuildDiagnostic({
message: 'Do not support Pattern. Please make sure enablePattern is set to true.',
range: utteranceAndEntities.range
});
throw (new exception(retCode.errorCode.INVALID_INPUT, error.toString(), [error]));
}
utterance = handleAtForPattern(utterance, entitiesFound, parsedContent.LUISJsonStructure.flatListOfEntityAndRoles);