How to use @accordproject/ergo-compiler - 10 common examples

To help you get started, we’ve selected a few @accordproject/ergo-compiler 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 / template-studio-v2 / src / sagas / modelSaga.js View on Github external
export function* validateClauseModelFiles(action) {
  const { clauseTemplateId } = action;

  // get all the model files for a template
  const clauseTemplates = yield select(clauseTemplateSelectors.clauseTemplates);
  const modelFiles = clauseTemplates[clauseTemplateId].model;

  try {
    // create a new ModelManager with the template's concerto files
    const modelManager = new APModelManager();
    modelFiles.forEach((file) => {
      modelManager.addModelFile(file.content, file.name, true);
    });

    // download external dependencies
    yield modelManager.updateExternalModels();

    // validate the model manager
    modelManager.validateModelFiles();

    yield put(actions.updateModelManagerSuccess(modelManager));

    yield put(actions.updateModelManagerError(null, clauseTemplateId));
  } catch (err) {
    err.type = 'Model';
    err.fileName = action.fileName;
github accordproject / cicero / packages / cicero-core / src / metadata.js View on Github external
if(!semver.valid(semver.coerce(packageJson.version))){
            throw new Error('The template version must be a valid semantic version (semver) number.');
        }

        this.ciceroVersion = packageJson.accordproject.cicero;

        if (!this.satisfiesCiceroVersion(ciceroVersion)){
            const msg = `The template targets Cicero version ${this.ciceroVersion} but the current Cicero version is ${ciceroVersion}.`;
            Logger.error(msg);
            throw new Error(msg);
        }

        // the runtime property is optional, and is only mandatory for templates that have been compiled
        if (packageJson.accordproject.runtime && packageJson.accordproject.runtime !== 'ergo') {
            ErgoCompiler.isValidTarget(packageJson.accordproject.runtime);
        } else {
            packageJson.accordproject.runtime = 'ergo';
        }
        this.runtime = packageJson.accordproject.runtime;

        if(!samples || typeof(samples) !== 'object') {
            throw new Error('sample.md is required');
        }

        if(request && typeof(request) !== 'object') {
            throw new Error('request.json must be an object');
        }

        if (!packageJson.name || !this._validName(packageJson.name)) {
            throw new Error ('template name can only contain lowercase alphanumerics, _ or -');
        }
github accordproject / cicero / packages / cicero-core / src / templateloader.js View on Github external
* distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const fs = require('fs');
const fsPath = require('path');
const slash = require('slash');
const JSZip = require('jszip');
const xregexp = require('xregexp');
const languageTagRegex = require('ietf-language-tag-regex');
const DefaultArchiveLoader = require('./loaders/defaultarchiveloader');
const FileLoader = require('@accordproject/ergo-compiler').FileLoader;
const Logger = require('@accordproject/concerto-core').Logger;

// Matches 'sample.md' or 'sample_TAG.md' where TAG is an IETF language tag (BCP 47)
const IETF_REGEXP = languageTagRegex({ exact: false }).toString().slice(1,-2);
const SAMPLE_FILE_REGEXP = xregexp('text[/\\\\]sample(_(' + IETF_REGEXP + '))?.md$');

/**
 * A utility class to create templates from data sources.
 * @class
 * @private
 * @abstract
 */
class TemplateLoader extends FileLoader {
    /**
     * Create a template from an archive.
     * @param {*} Template - the type to construct
github accordproject / cicero / packages / cicero-core / src / templateinstance.js View on Github external
* http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const Logger = require('@accordproject/concerto-core').Logger;
const ParseException = require('@accordproject/concerto-core').ParseException;
const crypto = require('crypto');
const ErrorUtil = require('./errorutil');
const Util = require('@accordproject/ergo-compiler').Util;
const moment = require('moment-mini');
// Make sure Moment serialization preserves utcOffset. See https://momentjs.com/docs/#/displaying/as-json/
moment.fn.toJSON = Util.momentToJson;
const TemplateLoader = require('./templateloader');
const ErgoEngine = require('@accordproject/ergo-engine/index.browser.js').EvalEngine;

/**
 * A TemplateInstance is an instance of a Clause or Contract template. It is executable business logic, linked to
 * a natural language (legally enforceable) template.
 * A TemplateInstance must be constructed with a template and then prior to execution the data for the clause must be set.
 * Set the data for the TemplateInstance by either calling the setData method or by
 * calling the parse method and passing in natural language text that conforms to the template grammar.
 * @public
 * @abstract
 * @class
 */
github accordproject / cicero / packages / cicero-core / src / templateinstance.js View on Github external
* distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const Logger = require('@accordproject/concerto-core').Logger;
const ParseException = require('@accordproject/concerto-core').ParseException;
const crypto = require('crypto');
const ErrorUtil = require('./errorutil');
const Util = require('@accordproject/ergo-compiler').Util;
const moment = require('moment-mini');
// Make sure Moment serialization preserves utcOffset. See https://momentjs.com/docs/#/displaying/as-json/
moment.fn.toJSON = Util.momentToJson;
const TemplateLoader = require('./templateloader');
const ErgoEngine = require('@accordproject/ergo-engine/index.browser.js').EvalEngine;

/**
 * A TemplateInstance is an instance of a Clause or Contract template. It is executable business logic, linked to
 * a natural language (legally enforceable) template.
 * A TemplateInstance must be constructed with a template and then prior to execution the data for the clause must be set.
 * Set the data for the TemplateInstance by either calling the setData method or by
 * calling the parse method and passing in natural language text that conforms to the template grammar.
 * @public
 * @abstract
 * @class
 */
class TemplateInstance {

    /**
github accordproject / cicero / packages / cicero-core / src / templateinstance.js View on Github external
parse(input, currentTime, fileName) {
        let text = TemplateLoader.normalizeText(input);
        // Roundtrip the sample through the Commonmark parser
        text = this.getTemplate().getParserManager().roundtripMarkdown(text);

        // Set the current time and UTC Offset
        const now = Util.setCurrentTime(currentTime);
        const utcOffset = now.utcOffset();

        let parser = this.getTemplate().getParserManager().getParser();
        try {
            parser.feed(text);
        } catch(err) {
            const fileLocation = ErrorUtil.locationOfError(err);
            throw new ParseException(err.message, fileLocation, fileName, err.message, 'cicero-core');
        }
        if (parser.results.length !== 1) {
            const head = JSON.stringify(parser.results[0]);

            parser.results.forEach(function (element) {
                if (head !== JSON.stringify(element)) {
                    const err = `Ambiguous text. Got ${parser.results.length} ASTs for text: ${text}`;
                    throw new ParseException(err, null, fileName, err, 'cicero-core' );
github accordproject / cicero / packages / cicero-core / src / scriptmanager.js View on Github external
compileLogic() {
        let sourceErgo = this.getLogic();
        if (sourceErgo === undefined || sourceErgo.length === 0) {
            return null;
        }
        const compiledErgo = ErgoCompiler.compileToJavaScript(sourceErgo,this.modelManager.getModels(),'cicero',true);
        //console.log('compiling' + this.contents);
        if (compiledErgo.hasOwnProperty('error')) {
            throw new Error(ErgoCompiler.ergoVerboseErrorToString(compiledErgo.error));
        }
        this.compiledScript = new Script(this.modelManager, 'main.js', '.js', compiledErgo.success);
        return this.compiledScript;
    }
github accordproject / cicero / packages / cicero-core / src / scriptmanager.js View on Github external
compileLogic() {
        let sourceErgo = this.getLogic();
        if (sourceErgo === undefined || sourceErgo.length === 0) {
            return null;
        }
        const compiledErgo = ErgoCompiler.compileToJavaScript(sourceErgo,this.modelManager.getModels(),'cicero',true);
        //console.log('compiling' + this.contents);
        if (compiledErgo.hasOwnProperty('error')) {
            throw new Error(ErgoCompiler.ergoVerboseErrorToString(compiledErgo.error));
        }
        this.compiledScript = new Script(this.modelManager, 'main.js', '.js', compiledErgo.success);
        return this.compiledScript;
    }
github accordproject / cicero / packages / cicero-core / src / metadata.js View on Github external
* you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const Logger = require('@accordproject/concerto-core').Logger;
const ErgoCompiler = require('@accordproject/ergo-compiler').Compiler;
const ciceroVersion = require('../package.json').version;
const semver = require('semver');

const templateTypes = {
    CONTRACT: 0,
    CLAUSE: 1
};

/**
 * Defines the metadata for a Template, including the name, version, README markdown.
 * @class
 * @public
 */
class Metadata {

    /**
github accordproject / cicero / packages / cicero-core / src / scriptmanager.js View on Github external
* you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const Script = require('./script');
const ErgoCompiler = require('@accordproject/ergo-compiler').Compiler;

/**
 * <p>
 * Manages a set of scripts.
 * </p>
 * @private
 * @class
 * @memberof module:cicero-core
 */
class ScriptManager {

    /**
     * Create the ScriptManager.
     * <p>
     * <strong>Note: Only to be called by framework code. Applications should
     * retrieve instances from {@link BusinessNetworkDefinition}</strong></p>