How to use @accordproject/concerto-core - 10 common examples

To help you get started, we’ve selected a few @accordproject/concerto-core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github accordproject / cicero / packages / cicero-core / src / parsermanager.js View on Github external
rules : []
        };
        const gv = new GrammarVisitor();
        this.template.getModelManager().accept(gv, parameters);
        parts.modelRules.push(...parameters.rules);

        // combine the results
        nunjucks.configure(fsPath.resolve(__dirname), {
            tags: {
                blockStart: '<%',
                blockEnd: '%>'
            },
            autoescape: false  // Required to allow nearley syntax strings
        });
        const combined = nunjucks.render('template.ne', parts);
        Logger.debug('Generated template grammar' + combined);

        // console.log(combined);
        this.setGrammar(combined);
        this.templatizedGrammar = templatizedGrammar;
    }
github accordproject / cicero / packages / cicero-cli / lib / commands.js View on Github external
.then(async (template) => {
                // Initialize clause
                clause = new Clause(template);
                clause.parse(sampleText, currentTime);

                let stateJson;
                if(!fs.existsSync(statePath)) {
                    Logger.warn('A state file was not provided, initializing state. Try the --state flag or create a state.json in the root folder of your template.');
                    const initResult = await engine.init(clause, currentTime);
                    stateJson = initResult.state;
                } else {
                    stateJson = JSON.parse(fs.readFileSync(statePath, 'utf8'));
                }

                // First execution to get the initial response
                const firstRequest = requestsJson[0];
                const initResponse = engine.trigger(clause, firstRequest, stateJson, currentTime);
                // Get all the other requests and chain execution through Promise.reduce()
                const otherRequests = requestsJson.slice(1, requestsJson.length);
                return otherRequests.reduce((promise,requestJson) => {
                    return promise.then((result) => {
                        return engine.trigger(clause, requestJson, result.state);
                    });
                }, initResponse);
github accordproject / cicero / packages / cicero-core / src / templateloader.js View on Github external
const requestContents = await TemplateLoader.loadZipFileContents(zip, 'request.json', true);
        const packageJsonObject = await TemplateLoader.loadZipFileContents(zip, 'package.json', true, true);
        const templatizedGrammar = await TemplateLoader.loadZipFileContents(zip, 'text/grammar.tem.md', false, false);

        Logger.debug(method, 'Looking for model files');
        let ctoFiles =  await TemplateLoader.loadZipFilesContents(zip, /model[/\\].*\.cto$/);
        ctoFiles.forEach(async (file) => {
            ctoModelFileNames.push(file.name);
            ctoModelFiles.push(file.contents);
        });

        // create the template
        const template = new (Function.prototype.bind.call(Template, null, packageJsonObject, readmeContents, sampleTextFiles, requestContents, options));

        // add model files
        Logger.debug(method, 'Adding model files to model manager');
        template.getModelManager().addModelFiles(ctoModelFiles, ctoModelFileNames, true); // validation is disabled

        Logger.debug(method, 'Setting grammar');
        if(!templatizedGrammar) {
            throw new Error('A template must contain a grammar.tem.md file.');
        } else {
            template.parserManager.buildGrammar(templatizedGrammar);
        }

        // load and add the ergo files
        if(template.getMetadata().getRuntime() === 'ergo') {
            template.getLogicManager().addTemplateFile(templatizedGrammar,'text/grammar.tem.md');
            Logger.debug(method, 'Adding Ergo files to script manager');
            const scriptFiles = await TemplateLoader.loadZipFilesContents(zip, /logic[/\\].*\.ergo$/);
            scriptFiles.forEach(function (obj) {
                template.getLogicManager().addLogicFile(obj.contents, obj.name);
github accordproject / cicero / packages / cicero-core / src / templateloader.js View on Github external
// add model files
        Logger.debug(method, 'Adding model files to model manager');
        template.getModelManager().addModelFiles(ctoModelFiles, ctoModelFileNames, true); // validation is disabled

        Logger.debug(method, 'Setting grammar');
        if(!templatizedGrammar) {
            throw new Error('A template must contain a grammar.tem.md file.');
        } else {
            template.parserManager.buildGrammar(templatizedGrammar);
        }

        // load and add the ergo files
        if(template.getMetadata().getRuntime() === 'ergo') {
            template.getLogicManager().addTemplateFile(templatizedGrammar,'text/grammar.tem.md');
            Logger.debug(method, 'Adding Ergo files to script manager');
            const scriptFiles = await TemplateLoader.loadZipFilesContents(zip, /logic[/\\].*\.ergo$/);
            scriptFiles.forEach(function (obj) {
                template.getLogicManager().addLogicFile(obj.contents, obj.name);
            });
        } else {
            // load and add compiled JS files - we assume all runtimes are JS based (review!)
            Logger.debug(method, 'Adding JS files to script manager');
            const scriptFiles = await TemplateLoader.loadZipFilesContents(zip, /logic[/\\].*\.js$/);
            scriptFiles.forEach(function (obj) {
                template.getLogicManager().addLogicFile(obj.contents, obj.name);
            });
        }

        // check the integrity of the model and logic of the template
        template.validate();
github accordproject / cicero / packages / cicero-core / src / loaders / httparchiveloader.js View on Github external
load(requestUrl, options) {

        if(!options) {
            options = {};
        }
        Logger.debug('Loading archive at: ' + requestUrl);
        const request = JSON.parse(JSON.stringify(options));
        request.url = requestUrl;
        request.method = 'get';
        request.responseType = 'arraybuffer'; // Necessary for binary archives
        request.timeout = 5000;

        return axios(request)
            .then((response) => {
                return response.data;
            }).catch(function (error) {
                if (error.response) {
                    // The request was made and the server responded with a status code
                    // that falls out of the range of 2xx
                    Logger.debug('HTTPArchiveLoader.load (Error Response)',error.response.status);
                    Logger.debug('HTTPArchiveLoader.load (Error Response)',error.response.headers);
                    throw new Error('Request to URL ['+ requestUrl +'] returned with error code: ' + error.response.status);
github accordproject / cicero / packages / cicero-core / src / loaders / httparchiveloader.js View on Github external
}).catch(function (error) {
                if (error.response) {
                    // The request was made and the server responded with a status code
                    // that falls out of the range of 2xx
                    Logger.debug('HTTPArchiveLoader.load (Error Response)',error.response.status);
                    Logger.debug('HTTPArchiveLoader.load (Error Response)',error.response.headers);
                    throw new Error('Request to URL ['+ requestUrl +'] returned with error code: ' + error.response.status);
                } else if (error.request) {
                    // The request was made but no response was received
                    // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
                    // http.ClientRequest in node.js
                    Logger.debug('HTTPArchiveLoader.load (NoResponse)',error.request);
                    throw new Error('Server did not respond for URL ['+ requestUrl +']');
                } else {
                    // Something happened in setting up the request that triggered an Error
                    Logger.debug('HTTPArchiveLoader.load (Error)',error.message);
                    throw new Error('Error when accessing URL ['+ requestUrl +'] ' + error.message);
                }
            });
    }
github accordproject / cicero / packages / cicero-core / src / templateloader.js View on Github external
});

        // create the template
        const template = new (Function.prototype.bind.call(Template, null, packageJsonObject, readmeContents, sampleTextFiles, requestJsonObject, options));
        const modelFiles = [];
        const modelFileNames = [];
        const ctoFiles = await TemplateLoader.loadFilesContents(path, /model[/\\].*\.cto$/);
        ctoFiles.forEach((file) => {
            modelFileNames.push(slash(file.name));
            modelFiles.push(file.contents);
        });

        template.getModelManager().addModelFiles(modelFiles, modelFileNames, true);
        if(!options.skipUpdateExternalModels){
            await template.getModelManager().updateExternalModels();
            Logger.debug(method, 'Added model files', modelFiles.length);

            const externalModelFiles = template.getModelManager().getModels();
            externalModelFiles.forEach(function (file) {
                fs.writeFileSync(path + '/model/' + file.name, file.content);
            });
        }


        // load and add the template
        let templatizedGrammar = await TemplateLoader.loadFileContents(path, 'text/grammar.tem.md', false, false);

        if(!templatizedGrammar) {
            throw new Error('A template must either contain a grammar.tem.md file.');
        } else {
            template.parserManager.buildGrammar(templatizedGrammar);
            Logger.debug(method, 'Loaded grammar.tem.md', templatizedGrammar);
github accordproject / cicero / packages / cicero-core / src / templateloader.js View on Github external
sampleFiles.forEach((file) => {
            const matches = file.name.match(SAMPLE_FILE_REGEXP);

            let locale = 'default';
            // Match found
            if(matches !== null && matches[2]){
                locale = matches[2];
            }
            Logger.debug(method, 'Using sample file locale', locale);
            sampleTextFiles[locale] = file.contents;
        });
github accordproject / cicero / packages / cicero-core / src / templateloader.js View on Github external
fs.writeFileSync(path + '/model/' + file.name, file.content);
            });
        }


        // load and add the template
        let templatizedGrammar = await TemplateLoader.loadFileContents(path, 'text/grammar.tem.md', false, false);

        if(!templatizedGrammar) {
            throw new Error('A template must either contain a grammar.tem.md file.');
        } else {
            template.parserManager.buildGrammar(templatizedGrammar);
            Logger.debug(method, 'Loaded grammar.tem.md', templatizedGrammar);
        }

        Logger.debug(method, 'Loaded grammar.tem.md');

        // load and add the ergo files
        if(template.getMetadata().getRuntime() === 'ergo') {
            // If Ergo then also register the template
            template.getLogicManager().addTemplateFile(templatizedGrammar,'text/grammar.tem.md');
            const ergoFiles = await TemplateLoader.loadFilesContents(path, /logic[/\\].*\.ergo$/);
            ergoFiles.forEach((file) => {
                const resolvedPath = slash(fsPath.resolve(path));
                const resolvedFilePath = slash(fsPath.resolve(file.name));
                const truncatedPath = resolvedFilePath.replace(resolvedPath+'/', '');
                template.getLogicManager().addLogicFile(file.contents, truncatedPath);
            });
        } else {
            // load and add compiled JS files - we assume all runtimes are JS based (review!)
            const jsFiles = await TemplateLoader.loadFilesContents(path, /logic[/\\].*\.js$/);
            jsFiles.forEach((file) => {
github accordproject / cicero / packages / cicero-core / src / templatelibrary.js View on Github external
async getTemplate(templateUri) {
        const cacheKey = this.getTemplateCacheKey(templateUri);

        const result = globalTemplateCache.get(cacheKey);
        if (result) {
            Logger.info('Returning template from cache', templateUri);
            return result;
        }

        const templateUriInfo = TemplateLibrary.parseURI(templateUri);
        const templateIndex = await this.getTemplateIndex();
        const templateMetadata = templateIndex[`${templateUriInfo.templateName}@${templateUriInfo.templateVersion}`];
        if(!templateMetadata) {
            throw new Error(`Failed to find template ${templateUri}`);
        }

        // fetch the template
        const template = await Template.fromUrl(templateMetadata.url);

        // check the hash matches
        const templateHash = template.getHash();
        if(templateHash !== templateUriInfo.templateHash) {