Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(decorator): added new methods to extract vocab or non-vocab decorators from model #888

Merged
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions packages/concerto-core/api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,12 @@ class Concerto {
+ string getNamespace(obj)
}
+ object setCurrentTime()
class DecoratorExtractor {
+ void constructor(boolean,string,string,Object)
}
class DecoratorManager {
+ ModelManager validate(decoratorCommandSet,ModelFile[]) throws Error
+ ModelManager decorateModels(ModelManager,decoratorCommandSet,object?,boolean?,boolean?,boolean?,boolean?)
+ ExtractDecoratorsResult extractDecorators(ModelManager,object,boolean,string)
+ ExtractDecoratorsResult extractVocabularies(ModelManager,object,boolean,string)
+ ExtractDecoratorsResult extractNonVocabDecorators(ModelManager,object,boolean,string)
+ void validateCommand(ModelManager,command)
+ Boolean falsyOrEqual(string||,string[])
+ void applyDecorator(decorated,string,newDecorator)
Expand Down
5 changes: 5 additions & 0 deletions packages/concerto-core/changelog.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@
# Note that the latest public API is documented using JSDocs and is available in api.txt.
#

Version 3.17.3 {1c15de121dd80375cf531bc2244efdd0} 2024-07-26
- Added new methods to extract vocab or non-vocab decorators from model
- Fixed some minor bugs related to vocabulary parsing
- Exposed method to validate locale

Version 3.17.2 {eb3903401fdcf7c26cca1f3f8a029171} 2024-07-17
- Added new optimized methods for decorating models with decorator commandsets
- fixed other decorator command set bugs
Expand Down
109 changes: 83 additions & 26 deletions packages/concerto-core/lib/decoratorextractor.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,46 @@ const { MetaModelNamespace } = require('@accordproject/concerto-metamodel');
* Utility functions to work with
* [DecoratorCommandSet](https://models.accordproject.org/concerto/decorators.cto)
* @memberof module:concerto-core
* @private
*/
class DecoratorExtractor {
sanketshevkar marked this conversation as resolved.
Show resolved Hide resolved
/**
* The action to be performed to extract all, only vocab or only non-vocab decorators
*/
static Action = {
sanketshevkar marked this conversation as resolved.
Show resolved Hide resolved
EXTRACT_ALL: 0,
EXTRACT_VOCAB: 1,
EXTRACT_NON_VOCAB: 2
};

/**
* Create the DecoratorExtractor.
* @constructor
* @param {boolean} removeDecoratorsFromModel - flag to determine whether to remove decorators from source model
* @param {string} locale - locale for extracted vocabularies
* @param {string} dcs_version - version string
* @param {Object} sourceModelAst - the ast of source models
* @param {int} [action=DecoratorExtractor.Action.EXTRACT_ALL] - the action to be performed
*/
constructor(removeDecoratorsFromModel, locale, dcs_version, sourceModelAst) {
constructor(removeDecoratorsFromModel, locale, dcs_version, sourceModelAst, action = DecoratorExtractor.Action.EXTRACT_ALL) {
this.extractionDictionary = {};
this.removeDecoratorsFromModel = removeDecoratorsFromModel;
this.locale = locale;
this.dcs_version = dcs_version;
this.sourceModelAst = sourceModelAst;
this.updatedModelAst = sourceModelAst;
this.action = Object.values(DecoratorExtractor.Action).includes(action)? action : DecoratorExtractor.Action.EXTRACT_ALL;
ekarademir marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Returns if the decorator is vocab or not
* @param {string} decoractorName - the name of decorator
* @returns {boolean} - returns true if the decorator is a vocabulary decorator else false
* @private
*/
isVocabDecorator(decoractorName) {
const vocabPattern = /^Term_/;
return decoractorName === 'Term' || vocabPattern.test(decoractorName);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think if you recreate the RegEx object at each call, it would be slower than just using startsWith. Is there a reason you want to put the vocabPattern in the function body?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are correct, we can use startWith instead of regex. Earlier it was having /^Term_/i as vocabPattern to check it in case insensitive manner.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could have also move the regex to constructor and use the compiled regex. There are trade offs using either

}
/**
* Adds a key-value pair to a dictionary (object) if the key exists,
Expand Down Expand Up @@ -105,18 +128,23 @@ class DecoratorExtractor {
Object.keys(vocabObject).forEach(decl =>{
if (vocabObject[decl].term){
strVoc += ` - ${decl}: ${vocabObject[decl].term}\n`;
const otherProps = Object.keys(vocabObject[decl]).filter((str)=>str !== 'term' && str !== 'propertyVocabs');
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a yaml library that we can use instead of directly parsing the string? Maybe not for this PR but that would help a lot.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can directly create the obj in expected yaml format and use the yaml library to stringify the object or parse the string to yaml obj.

const otherProps = Object.keys(vocabObject[decl]).filter((str)=>str !== 'term' && str !== 'propertyVocabs');
if(otherProps.length > 0){
if (!vocabObject[decl].term){
ekarademir marked this conversation as resolved.
Show resolved Hide resolved
strVoc += ` - ${decl}: ${decl}\n`;
}
otherProps.forEach(key =>{
strVoc += ` ${key}: ${vocabObject[decl][key]}\n`;
});
}
if (vocabObject[decl].propertyVocabs && Object.keys(vocabObject[decl].propertyVocabs).length > 0){
if (!vocabObject[decl].term){
if (!vocabObject[decl].term && otherProps.length === 0){
strVoc += ` - ${decl}: ${decl}\n`;
}
strVoc += ' properties:\n';
Object.keys(vocabObject[decl].propertyVocabs).forEach(prop =>{
strVoc += ` - ${prop}: ${vocabObject[decl].propertyVocabs[prop].term}\n`;
strVoc += ` - ${prop}: ${vocabObject[decl].propertyVocabs[prop].term || ''}\n`;
ekarademir marked this conversation as resolved.
Show resolved Hide resolved
const otherProps = Object.keys(vocabObject[decl].propertyVocabs[prop]).filter((str)=>str !== 'term');
otherProps.forEach(key =>{
strVoc += ` ${key}: ${vocabObject[decl].propertyVocabs[prop][key]}\n`;
Expand Down Expand Up @@ -205,6 +233,18 @@ class DecoratorExtractor {
dictVoc[decl.declaration].propertyVocabs[decl.property][extensionKey] = dcs.arguments[0].value;
}
}
else if (decl.mapElement !== ''){
if (!dictVoc[decl.declaration].propertyVocabs[decl.mapElement]){
dictVoc[decl.declaration].propertyVocabs[decl.mapElement] = {};
}
if (dcs.name === 'Term'){
dictVoc[decl.declaration].propertyVocabs[decl.mapElement].term = dcs.arguments[0].value;
}
else {
const extensionKey = dcs.name.split('Term_')[1];
dictVoc[decl.declaration].propertyVocabs[decl.mapElement][extensionKey] = dcs.arguments[0].value;
}
}
else {
if (dcs.name === 'Term'){
dictVoc[decl.declaration].term = dcs.arguments[0].value;
Expand All @@ -227,30 +267,57 @@ class DecoratorExtractor {
let vocabData = [];
Object.keys(this.extractionDictionary).forEach(namespace => {
const jsonData = this.extractionDictionary[namespace];
const patternToDetermineVocab = /^Term_/i;
let dcsObjects = [];
let vocabObject = {};
jsonData.forEach(obj =>{
const decos = JSON.parse(obj.dcs);
const target = this.constructTarget(namespace, obj);
decos.forEach(dcs =>{
if (dcs.name !== 'Term' && !patternToDetermineVocab.test(dcs.name)){
const isVocab = this.isVocabDecorator(dcs.name);
if (!isVocab && this.action !== DecoratorExtractor.Action.EXTRACT_VOCAB){
dcsObjects = this.parseNonVocabularyDecorators(dcsObjects, dcs, this.dcs_version, target);
}
else {
if (isVocab && this.action !== DecoratorExtractor.Action.EXTRACT_NON_VOCAB){
vocabObject = this.parseVocabularies(vocabObject, obj, dcs);
}
});
});
decoratorData = this.transformNonVocabularyDecorators(dcsObjects, namespace, decoratorData);
vocabData = this.transformVocabularyDecorators(vocabObject, namespace, vocabData);
if(this.action !== DecoratorExtractor.Action.EXTRACT_VOCAB){
decoratorData = this.transformNonVocabularyDecorators(dcsObjects, namespace, decoratorData);
}
if(this.action !== DecoratorExtractor.Action.EXTRACT_NON_VOCAB){
vocabData = this.transformVocabularyDecorators(vocabObject, namespace, vocabData);
}
});
return {
decoratorCommandSet: decoratorData,
vocabularies: vocabData
};
}

/**
* Filter vocab or non-vocab decorators
* @param {Object} decorators - the collection of decorators
* @returns {Object} - the collection of filtered decorators
* @private
*/
filterDecorators(decorators){
if(this.removeDecoratorsFromModel){
if (this.action === DecoratorExtractor.Action.EXTRACT_ALL){
return undefined;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't this return all the decorators?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if removeDecoratorsFromModel is true then it should return undefined to remove all the decorators from the model

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a disconnect between the Action and the logic then?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The action parameter specifies what to extract from the model (vocab decorators, non-vocab decorators, or both). Meanwhile, removeDecoratorsFromModel flag determines if the decorators should be deleted or not from the model itself after extraction.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function then can be called filterOutDecorators. And then, I think you can just return early if this.removeDecoratorsFromModel is false with the decorators and avoid wrapping the whole function definition in an if statement.

Otherwise it looks like the code is looking like doing the opposite of what the function is aiming to do.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated

}
else if(this.action === DecoratorExtractor.Action.EXTRACT_VOCAB){
return decorators.filter((dcs) => {
return !this.isVocabDecorator(dcs.name);
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return decorators.filter((dcs) => {
return !this.isVocabDecorator(dcs.name);
});
return decorators.filter((dcs) => !this.isVocabDecorator(dcs.name);
);

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated similar changes

}
else if(this.action === DecoratorExtractor.Action.EXTRACT_NON_VOCAB){
return decorators.filter((dcs) => {
return this.isVocabDecorator(dcs.name);
});
}
}
return decorators;
}
/**
* Process the map declarations to extract the decorators.
*
Expand All @@ -267,9 +334,7 @@ class DecoratorExtractor {
mapElement: 'KEY'
};
this.constructDCSDictionary(namespace, declaration.key.decorators, constructOptions);
if (this.removeDecoratorsFromModel){
declaration.key.decorators = undefined;
}
declaration.key.decorators = this.filterDecorators(declaration.key.decorators);
}
}
if (declaration.value){
Expand All @@ -279,9 +344,7 @@ class DecoratorExtractor {
mapElement: 'VALUE'
};
this.constructDCSDictionary(namespace, declaration.value.decorators, constructOptions);
if (this.removeDecoratorsFromModel){
declaration.value.decorators = undefined;
}
declaration.value.decorators = this.filterDecorators(declaration.value.decorators);
}
}
return declaration;
Expand All @@ -304,9 +367,7 @@ class DecoratorExtractor {
property: property.name
};
this.constructDCSDictionary(namespace, property.decorators, constructOptions );
}
if (this.removeDecoratorsFromModel){
property.decorators = undefined;
property.decorators = this.filterDecorators(property.decorators);
}
return property;
});
Expand All @@ -328,9 +389,7 @@ class DecoratorExtractor {
declaration: decl.name,
};
this.constructDCSDictionary(namespace, decl.decorators, constructOptions);
}
if (this.removeDecoratorsFromModel){
decl.decorators = undefined;
decl.decorators = this.filterDecorators(decl.decorators);
}
if (decl.$class === `${MetaModelNamespace}.MapDeclaration`) {
const processedMapDecl = this.processMapDeclaration(decl, namespace);
Expand All @@ -352,11 +411,9 @@ class DecoratorExtractor {
*/
processModels(){
const processedModels = this.sourceModelAst.models.map(model =>{
if ((model?.decorators.length > 0)){
if ((model?.decorators?.length > 0)){
this.constructDCSDictionary(model.namespace, model.decorators, {});
if (this.removeDecoratorsFromModel){
model.decorators = undefined;
}
model.decorators = this.filterDecorators(model.decorators);
}
const processedDecl = this.processDeclarations(model.declarations, model.namespace);
model.declarations = processedDecl;
Expand Down
55 changes: 47 additions & 8 deletions packages/concerto-core/lib/decoratormanager.js
Original file line number Diff line number Diff line change
Expand Up @@ -424,15 +424,11 @@ class DecoratorManager {
return newModelManager;
}
/**
* @typedef decoratorCommandSet
* @type {object}
* @typedef vocabularies
* @type {string}
* @typedef ExtractDecoratorsResult
* @type {object}
* @property {ModelManager} modelManager - A model manager containing models stripped without decorators
* @property {decoratorCommandSet} object[] - Stripped out decorators, formed into decorator command sets
* @property {vocabularies} object[] - Stripped out vocabularies, formed into vocabulary files
* @property {*} decoratorCommandSet - Stripped out decorators, formed into decorator command sets
* @property {string[]} vocabularies - Stripped out vocabularies, formed into vocabulary files
*/
/**
* Extracts all the decorator commands from all the models in modelManager
Expand All @@ -449,15 +445,58 @@ class DecoratorManager {
...options
};
const sourceAst = modelManager.getAst(true);
const decoratorExtrator = new DecoratorExtractor(options.removeDecoratorsFromModel, options.locale, DCS_VERSION, sourceAst);
const decoratorExtrator = new DecoratorExtractor(options.removeDecoratorsFromModel, options.locale, DCS_VERSION, sourceAst, DecoratorExtractor.Action.EXTRACT_ALL);
const collectionResp = decoratorExtrator.extract();
return {
modelManager: collectionResp.updatedModelManager,
decoratorCommandSet: collectionResp.decoratorCommandSet,
vocabularies: collectionResp.vocabularies
};
}

/**
* Extracts all the vocab decorator commands from all the models in modelManager
* @param {ModelManager} modelManager the input model manager
* @param {object} options - decorator models options
* @param {boolean} options.removeDecoratorsFromModel - flag to strip out vocab decorators from models
* @param {string} options.locale - locale for extracted vocabulary set
* @returns {ExtractDecoratorsResult} - a new model manager with/without the decorators and vocab yamls
*/
static extractVocabularies(modelManager,options) {
options = {
removeDecoratorsFromModel: false,
locale:'en',
...options
};
const sourceAst = modelManager.getAst(true);
const decoratorExtrator = new DecoratorExtractor(options.removeDecoratorsFromModel, options.locale, DCS_VERSION, sourceAst, DecoratorExtractor.Action.EXTRACT_VOCAB);
const collectionResp = decoratorExtrator.extract();
return {
modelManager: collectionResp.updatedModelManager,
vocabularies: collectionResp.vocabularies
sanketshevkar marked this conversation as resolved.
Show resolved Hide resolved
};
}
/**
* Extracts all the non-vocab decorator commands from all the models in modelManager
* @param {ModelManager} modelManager the input model manager
* @param {object} options - decorator models options
* @param {boolean} options.removeDecoratorsFromModel - flag to strip out non-vocab decorators from models
* @param {string} options.locale - locale for extracted vocabulary set
* @returns {ExtractDecoratorsResult} - a new model manager with/without the decorators and a list of extracted decorator jsons
*/
static extractNonVocabDecorators(modelManager,options) {
options = {
removeDecoratorsFromModel: false,
locale:'en',
...options
};
const sourceAst = modelManager.getAst(true);
const decoratorExtrator = new DecoratorExtractor(options.removeDecoratorsFromModel, options.locale, DCS_VERSION, sourceAst, DecoratorExtractor.Action.EXTRACT_NON_VOCAB);
const collectionResp = decoratorExtrator.extract();
return {
modelManager: collectionResp.updatedModelManager,
decoratorCommandSet: collectionResp.decoratorCommandSet
};
}
/**
* Throws an error if the decoractor command is invalid
* @param {ModelManager} validationModelManager the validation model manager
Expand Down
Loading
Loading